I want to convert an integer to the fractional part of a number using javascript.

For example:

  • 10030 -> 0.10030

  • 123 -> 0.123

I've come up with two ways of doing this:

var convertIntegerPartToFractionalPart1 = function(integerPart) {
    var fractionalPart = integerPart;

    while(fractionalPart > 1) {
        fractionalPart = fractionalPart / 10;
    }
    return fractionalPart;
};

var convertIntegerPartToFractionalPart2 = function(integerPart) {
    return parseFloat('.' + integerPart);
};

convertIntegerPartToFractionalPart1 does not produce 100% accurate results, for example 132232 is converted to 0.13223200000000002. However convertIntegerPartToFractionalPart1 is more than twice as fast as convertIntegerPartToFractionalPart2 under node.js on my MacBook Pro. (1000000 runs of convertIntegerPartToFractionalPart1 took 46ms, 1000000 runs of convertIntegerPartToFractionalPart2 took 96ms)

Is there a better way of doing this?

有帮助吗?

解决方案

I first didn't want to answer, as Pointys solution seems far more elegant.

But after doing a Jsperf it turned out the Math solution was about 70% slower for me on chrome.

function cnvrt3 (n) {
  return n / Math.pow(10,(""+n).length)
}
cnvrt3(132232)//0.132232 

So heres the same using casting to determine the power of ten

Note due to the floating point precision 0.132232 is not really 0.132232. Though most likely the value you are looking for

其他提示

Try this:

function cvt3(n) {
  return n / Math.pow(10, Math.ceil(Math.log(n)/Math.LN10));
}

It's still going to be possible that the result will not be exact, due to the nature of binary floating point (I think). But doing just one division might help. For smaller numbers your iteration might be just as good, and faster.

console.log( cvt3(132232) ); // 0.132232 

edit the version by Mr. Monosodium Glutamate is faster!

You won't maintain numbers with trailing zeroes, as in your example:

10030 ->0.10030

but you can prepend a dot in front of a string:

'.'+String(10030)-> '.10030'

Here is best approach to so this :

Demo Here

    function ab() {
        var a = 566123;

        var len = a.toString().length;
        var decimalPoints = 1;

        for (var i = 0; i < len; i++) {
            decimalPoints = decimalPoints * 10;
        }

        var number = parseInt(a) / decimalPoints;
        alert(number);
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top