0.5 时向上或向下舍入

Mer*_*erc 5 javascript math precision rounding

我对 Javascript 在达到 0.5 时四舍五入的方式有问题。我正在编写征费计算器,并注意到结果中有 0.1c 的差异。

问题是他们的结果是21480.705我的应用程序转换成的结果21480.71,而关税说21480.70

这就是我在 Javascript 中看到的:

(21480.105).toFixed(2)
"21480.10"
(21480.205).toFixed(2)
"21480.21"
(21480.305).toFixed(2)
"21480.31"
(21480.405).toFixed(2)
"21480.40"
(21480.505).toFixed(2)
"21480.51"
(21480.605).toFixed(2)
"21480.60"
(21480.705).toFixed(2)
"21480.71"
(21480.805).toFixed(2)
"21480.81"
(21480.905).toFixed(2)
"21480.90"
Run Code Online (Sandbox Code Playgroud)

问题:

  • 这种不稳定的路由到底是怎么回事?
  • 获得“四舍五入”结果(达到 0.5 时)的最快最简单方法是什么?

Jon*_*lms 0

您可以四舍五入为整数,然后在显示时换入逗号:

function round(n, digits = 2) {
  // rounding to an integer is accurate in more cases, shift left by "digits" to get the number of digits behind the comma
  const str = "" + Math.round(n * 10 ** digits);

  return str
    .padStart(digits + 1, "0") // ensure there are enough digits, 0 -> 000 -> 0.00
    .slice(0, -digits) + "." + str.slice(-digits); // add a comma at "digits" counted from the end
}
Run Code Online (Sandbox Code Playgroud)