Why max digits with decimal in JavaScript are only 16

前端 未结 2 1094
悲哀的现实
悲哀的现实 2020-12-12 04:11

I came across this issue a while back when I was testing some HTML forms. The Maximum number of digits in JavaScript Number with a decimal point is only 16

I have t

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 04:50

    In javascript You can't represent most decimal fractions exactly with binary floating point types (which is what ECMAScript uses to represent floating point value).

    This is why javascript uses 16 numbers after the decimal point. for example -

    Try to run:

    var x =  3.14159265358979323846;
    print(x.toFixed(20));
    

    and see the following is being cast to float.

    If you want to cast more then 16 points after the decimal point you can either:

    • Use literal string to represent your number
    • Use external libraries like math.js or BigInteger.js.

提交回复
热议问题