我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
我想最多四舍五入两位小数,但只有在必要时。
输入:
10
1.7777777
9.1
输出:
10
1.78
9.1
如何在JavaScript中执行此操作?
当前回答
+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12
(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12
其他回答
根据评论中已给出的答案,链接至http://jsfiddle.net/AsRqx/,下面的一个对我来说很好。
function C(num)
{
return +(Math.round(num + "e+2") + "e-2");
}
function N(num, places)
{
return +(Math.round(num + "e+" + places) + "e-" + places);
}
C(1.005);
N(1.005, 0);
N(1.005, 1); // Up to 1 decimal places
N(1.005, 2); // Up to 2 decimal places
N(1.005, 3); // Up to 3 decimal places
const formattedNumber=数学舍入(数字*100)/100;
我正在构建一个简单的tipCalculator,这里有很多答案似乎使问题过于复杂。所以我发现总结这个问题是真正回答这个问题的最佳方式。
如果要创建舍入的十进制数,首先调用Fixed(要保留的小数位数),然后将其包装在number()中。
最终结果是:
let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip) // 57.29 instead of 57.288
具有可读选项的函数更直观:
function round_number(options) {
const places = 10**options.decimal_places;
const res = Math.round(options.number * places)/places;
return(res)
}
用法:
round_number({
number : 0.5555555555555556,
decimal_places : 3
})
0.556
这对我(TypeScript)起到了作用:
round(decimal: number, decimalPoints: number): number{
let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);
console.log(`Rounded ${decimal} to ${roundedValue}`);
return roundedValue;
}
样本输出
Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28