如何将以下输入转换为下面的输出
输入
1.0789
10.350
1.7777
输出
1.07
10.35
1.77
如何将以下输入转换为下面的输出
输入
1.0789
10.350
1.7777
输出
1.07
10.35
1.77
使用Math.floor
将当前值下的小数位四舍五入。
示例
Math.floor(1.0789 * 100) / 100
工作的Fiddle
console.log(Math.floor(1.0789 * 100) / 100);
console.log(Math.floor(10.350 * 100) / 100);
console.log(Math.floor(1.7777 * 100) / 100);
console.log(Math.floor(12.34 * 100) / 100);
function floorDecimals(value, decimals) { return Number(Math.floor(value+'e'+decimals)+'e-'+decimals); }
。原文出处在这里http://www.jacklmoore.com/notes/rounding-in-javascript/。 - Sean TomlinsMath.floor(3.29012 + 'e' + 3)
TypeScript 错误 - "类型为 'string' 的参数不能赋值给类型为 'number' 的参数。" - Fiddle Freak12.34
会出问题吗?我已经在最新的 Chrome、Edge 和 IE 上测试了这个解决方案,它仍然像预期的那样工作。 - Nitheesh你有几种方法可以实现这个功能
toFixed
将它们四舍五入到小数点后的位数。 - AlberttoFixed
函数会对5及以上的小数进行四舍五入,只有在小于等于4时才会向下取整。 - JChaotoFixed
返回一个字符串。 - Matyanson
after=Math.floor(before*100)/100
- Ultimater