Javascript - 如何显示被四舍五入后有一个小数点的整数。

问题描述 投票:0回答:1

我正在使用一个映射函数来返回四舍五入的小数点。有几个数字是返回整数的,如 index 2. 4 and index 3. 1 我试图让这些个位数返回小数点。所以,比如说,让 index 2: 4 -> 4.0; index 3. 1 -> 1.0

我曾尝试用 toFixed 函数,但它会影响所有其他有小数点的数字。如何在不影响数组中其他索引的情况下返回4.0和1.0?

我希望这些数字以整数的形式返回,当只使用toFixed时,我以字符串的形式返回这些数字。

我的预期结果是: 4.4, 4.6, 4.0, 1.0, 1.7

let sumRounded = sumPercentage.map(function (percent) {
  return Math.round(percent * 10) / 10;
});

原来的 console.log 。

0: 4.4
1: 4.6
2: 4
3: 1
4: 1.7

let sumRounded = sumPercentage.map(function (percent) {
  return Math.round((percent * 10) / 10).toFixed(1);
});

使用toFixed后的控制台日志

0: "4.0"
1: "5.0"
2: "4.0"
3: "1.0"
4: "2.0"
javascript arrays numbers
1个回答
0
投票

你的括号给了你错误的结果。

Math.round((percent * 10) / 10)

这是对整数的四舍五入,这就是为什么你所有的结果都以'.0'结尾。你要的是:

return (Math.round(percent * 10) / 10).toFixed(1);
© www.soinside.com 2019 - 2024. All rights reserved.