javascript - javaScript 使用 toFixed 舍入小数
问题描述
我遇到了使用 toFixed 在 JavaScript 中舍入小数的问题。
const num1 = (100.555).toFixed(2) // "100.56"
const num2 = (10.555).toFixed(2) // "10.55"
谁能解释为什么会发生这种行为?为什么第一个示例将小数舍入为 56,而第二个示例将其变为 55?
更新:如果我添加 4 位小数,则舍入不同。
const num3 = (10.5555).toFixed(2) // "10.56"
解决方案
这应该可以解决您的问题
// its a rounding bug it can be compenstated by representing numbers exactly in decimal notation.
Number.prototype.toFixedDown = function(digits) {
var re = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)"),
m = this.toString().match(re);
return m ? parseFloat(m[1]) : this.valueOf();
};
const num1 = 100.555.toFixedDown(2)
const num2 = (10.555).toFixedDown(2)
alert(num1+ ' ' + num2);
推荐阅读
- java - Java:如何解析 csv 文件以比较列中的数据
- android - android MapView + ViewPager2 + DataBinding 问题
- php - URL 路径重定向到主页,但在 PHP 中获取路径信息
- ios - 在 UITableView 中滚动时第一个和最后一个单元格更改颜色
- javascript - JavaScript URL searchParams 不返回任何内容
- ansible - Ansible 中的布尔启动参数
- corda - 更新到 Corda Enterprise - Web 服务器是否应将 CE 作为依赖项包含在内?
- linux - 如何使用 sed 在每个空格后添加一些文本?
- c++ - 在 C++ 中调用时对内联汇编代码的未定义引用
- android - 为什么导航图 ID 未在 R.id 中列出?