every time i use the Math.round(4.45678765e-6 * 10000)/10000 it gi开发者_如何学编程ves me a 0 value but if i remove the e-6 it gives the correct answer 4.4567 what shoul i do? here's my code. the value has the power of 10 something like this 4.45678765x10^-6.
<html>
<script type="text/javascript">
var x = Math.floor (4.45678765 * 10000)/10000;
document.write (x);
</script>
</html>
is it even possible to limit the decimal places if the value has an exponent?
4.45678765e-6
is 0.00000445678765
, that number with only five digits after decimal point is 0.00000
so JavaScript is giving you the correct result.
try .toPrecision(5) instead. IE: (4.45678765).toPrecision(5)
use 'numObj.toExponential([fractionDigits])'
your case is its raison d'être, and this overlooked gem seems to be a javascript method rarely given its due!
Quote from MDN:
Returns a string representing a Number object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point
More simply put, it limits the number of decimal places to show in exponential notation.
var x = 4.45678765e-6.toExponential(5) //returns 4.45679e-6
var x = 4.45678765e-6.toExponential(2) //returns 4.46e-6
See examples of more rounding with exponential notation here: https://stackoverflow.com/a/36532545/5440638
You can use -
var x = Number((4.45678765 * 10000)/10000).toFixed(5);
The toFixed( <digit> )
will restrict your value to those digits after decimal point.
Not 100% sure what your after but if you want the power;
var f = 4.45678765e-6;
var exp = Math.floor(Math.log(Math.abs(f)) / Math.LN10);
// -6
var f2 = f * Math.pow(10, -exp);
// 4.45678765
精彩评论