For instance, I have float 1.1111111111 and need to get 11111111111 and 10.

I want to avoid functions, which may change part after point as I need it to show metric prefixes.

It may look simple with strings, I am just not sure if it is a proper way in JavaScript.

有帮助吗?

解决方案

The modular division operator '%' can be used to get the remainder of a division in JS. This means that if we perform the modular division of a floating point number by 1, we get the value after the decimal point. Further, if we build a loop where we multiply by 10 until there is no longer anything after the decimal point, we can find the smallest power of ten we can multiply the original number by to get an integer.

Example below:

function getE(floatingPointValue)
{
    var x = floatingPointValue;
    var digitsAfterDecimal = 0;
    while(x % 1 != 0)
    {
        x = x * 10;
        digitsAfterDecimal++;
    }
    return x.toString() + " *10^-" + digitsAfterDecimal;
}

Fiddle: http://jsfiddle.net/L8XtP/2/

Hope this helps!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top