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?