gpt4 book ai didi

javascript - JS - 格式数字,小数点后两位不四舍五入

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:33:38 28 4
gpt4 key购买 nike

我会将数字格式化为保留 2 位小数而不四舍五入。所以我排除了 toFixed() 函数。

我试过这种方式

a = 1,809999
b = 27,94989

a = Math.floor(a * 100) / 100; --> 1,8
b = Math.floor(b * 100) / 100; --> 27,94

OR

a = Number(a.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 1,8
b = Number(b.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 27,94

不幸的是,a的小数点后第二位是零,这个被删了,我怎么能保留它,让a = 1.80呢?谢谢

最佳答案

(Math.floor(a * 100) / 100).toFixed(2);

使用 toFixed(2) !

JSFIDDLE DEMO

关于javascript - JS - 格式数字,小数点后两位不四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29941224/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com