在 Javascript 中将钱四舍五入到最接近的 10 美元

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3463920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:44:31  来源:igfitidea点击:

Round money to nearest 10 dollars in Javascript

javascriptdecimalroundingcurrency

提问by Marko

How can I round a decimal number in Javascript to the nearest 10? My math is pretty rubbish today, it could be the 2 hour sleep :/

如何将 Javascript 中的十进制数四舍五入到最接近的 10?我今天的数学很垃圾,可能是睡了两个小时:/

Some sample cases

一些示例案例

23.66  = 20
2.11 = 0
.49 = 

I understand I probably need a combination of Math.round/floor but I can't seem to get expected result.

我知道我可能需要 Math.round/floor 的组合,但我似乎无法得到预期的结果。

Any help/pointers appreciated!

任何帮助/指针表示赞赏!

M

回答by Toby

Try

尝试

Math.round(val / 10) * 10;

回答by Sebastián Grignoli

Use this function:

使用这个功能:

function roundTen(number)
{
  return Math.round(number/10)*10;
}



alert(roundTen(2823.66));

回答by paxdiablo

To round a number to the nearest 10, first divide it by 10, then round it to the nearest 1, then multiply it by 10 again:

要将数字四舍五入到最接近的 10,首先将其除以 10,然后将其四舍五入到最接近的 1,然后再次乘以 10:

val = Math.round(val/10)*10;

This pagehas some details. They go the other way (e.g., rounding to the nearest 0.01) but the theory and practice are identical - multiply (or divide), round, then divide (or multiply).

这个页面有一些细节。他们走另一条路(例如,四舍五入到最接近的 0.01),但理论和实践是相同的 - 乘(或除),舍入,然后除(或乘)。

回答by morgancodes

10 * Math.round(val / 10)

10 * Math.round(val / 10)

回答by yckart

function round(number, multiplier) {
  multiplier = multiplier || 1;
  return Math.round(number / multiplier) * multiplier;
}

var num1 = 2823.66;
var num2 = 142.11;
var num3 = 9.49;

console.log(
  "%s\n%s\n%s", // just a formating thing
  round(num1, 10), // 2820
  round(num2, 10), // 140
  round(num3, 10)  // 10
);