문제

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