JavaScript: represents float as the product of an integer and the power of ten

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

I want to avoid functions that can change part by point, as I need it to display metric prefixes.

It may look just like using strings, I'm just not sure if this is the right way in JavaScript.

+4
source share
1 answer

The modular division operator '%' can be used to get the remainder of division in JS. This means that if we do modular division of a floating point number by 1, we get the value after the decimal point. In addition, if we build a cycle where we multiply by 10 until after the decimal point nothing else works out, we can find the smallest power of ten, we can multiply the original number by integers.

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!

+8
source

Source: https://habr.com/ru/post/1481804/


All Articles