limit the decimal place in javascript is not working for 4.45678765e-6

前端 未结 5 785
执念已碎
执念已碎 2021-01-27 04:39

every time i use the Math.round(4.45678765e-6 * 10000)/10000 it gives 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. t

5条回答
  •  -上瘾入骨i
    2021-01-27 05:04

    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

提交回复
热议问题