Getting place values of a number w/ modulus?

前提是你 提交于 2019-12-07 09:36:34

问题


  • I need to get the place value of a random number submitted by a user. This number can by anything from 0-1000000000000000 (zero to one trillion).

  • I think this can be achieved by using the JavaScript modulus % operator. The problem, I don't really know how to use it, nor do I understand it.

  • Here is the Fiddle.

(All I know is 10%3 returns 1 because 3*3 = 9 and 10-9 = 1)

I figured out the ones, tens, hundreds, and thousands:

var ones = Math.floor(num % 10),
    tens = Math.floor(num / 10 % 10),
    hundreds = Math.floor(num / 100 % 10),
    thousands = Math.floor(num % 10000 / 1000);

I just need:

  1. Ten thousands
  2. Hundred thousands
  3. Millions
  4. Ten millions
  5. Hundred millions
  6. Billions
  7. Ten billions
  8. Hundred billions
  9. Trillions

-- I don't even know if this is possible for the rest, but if you have any hints or find at least one, let me know! Thank you.


回答1:


        var ones = Math.floor(num % 10),
            tens = Math.floor(num/10 % 10),
            hundreds = Math.floor(num/100 % 10),
            thousands = Math.floor(num/1000 % 10),
            tenThousands = Math.floor(num / 10000 % 10),
            hundredThousands = Math.floor(num / 100000 % 10),
            millions = Math.floor(num / 1000000 % 10),
            tenMillions = Math.floor(num / 10000000 % 10),
            hundredMillions = Math.floor(num / 100000000 % 10);

Managed to get to 100 million.




回答2:


var scaleStepWidth = 0;
var number = Math.ceil(1052220420.32);
var placeValue = 1;
for(i=0;i<(number.toString().length-1);i++){
    placeValue *= 10;
}
scaleStepWidth = eval(number.toString()[0])*placeValue;


来源:https://stackoverflow.com/questions/24226324/getting-place-values-of-a-number-w-modulus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!