Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: represent float as product of integer and power of ten

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.

like image 701
ISE Avatar asked Feb 16 '23 11:02

ISE


1 Answers

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!

like image 123
JessieArr Avatar answered Apr 27 '23 16:04

JessieArr