Skip to content
欢迎扫码关注公众号

JavaScript 浮点型加法的奇怪现象

javascript
var a = 6.65;
var b = 9.8;
var c = a + b;

结果c的值为 16.450000000000003

Why?


JavaScript 数字精度丢失问题总结


js
// toFixed 修复
function toFixed(num, s) {
    var times = Math.pow(10, s)
    var des = num * times + 0.5
    des = parseInt(des, 10) / times
    return des + ''
}

在这篇文章的末尾还发现了一个有趣的网站 0.30000000000000004.com

不止 js 有这种问题,C# 和 java 中都有同样的问题。

csharp
Console.WriteLine("{0:r}", .1 + .2);
Console.WriteLine("{0:f}", .1m + .2m);

输出结果为 :

> 0.30000000000000004
0.30

还有一篇很专业的论文:What Every Computer Scientist Should Know About Floating-Point Arithmetic

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.