javascript - 如何在javascript中舍入十进制数
问题描述
我有这个十进制数:1.12346
我现在只想保留 4 位小数,但我想四舍五入,所以它会返回:1.1234。现在它返回: 1.1235 这是错误的。
有效。我想要最后两个数字:“46”向下舍入到“4”而不是“5”
这怎么可能?
var nums = 1.12346;
nums = MathRound(nums, 4);
console.log(nums);
function MathRound(num, nrdecimals) {
return num.toFixed(nrdecimals);
}
解决方案
如果你这样做是因为你需要打印/显示一个值,那么我们不需要留在数字领域:把它变成一个字符串,然后把它切碎:
let nums = 1.12346;
// take advantage of the fact that
// bit operations cause 32 bit integer conversion
let intPart = (nums|0);
// then get a number that is _always_ 0.something:
let fraction = nums - intPart ;
// and just cut that off at the known distance.
let chopped = `${fraction}`.substring(2,6);
// then put the integer part back in front.
let finalString = `${intpart}.${chopped}`;
当然,如果您不是为了演示而这样做,那么可能应该首先回答“您为什么认为您需要这样做”(因为它使涉及该数字的后续数学无效)的问题,因为帮助您做错事是实际上并没有帮助,而是使事情变得更糟。
推荐阅读
- python - 如何检查变量是否为整数?
- deepstream.io - 尝试通过 npm 安装 deepstream.io
- python - 在 Jupyter Notebook 上加载 plotly updatemenus 时,如何仅显示一个跟踪?
- vue.js - 如果在 vuejs 中第一次选择,则禁用日期
- java - 无法访问在 Java 中作为参数传递的部分字节数组
- grep - 使用正则表达式从 txt 文件中提取内容
- javascript - 从字符串中生成最多 32 个字节的 substirng
- php - 如何从 CodeIgniter 和 MySql 表中统计调查的房屋数量
- windows-10 - 未安装 SMB 服务
- mongodb - MongoDB - 匹配多个字段相同的值