1

丸めと数値の書式設定が必要なコードに取り組んでいましたが、単体テストを書いているときに、この奇妙なケースに遭遇しました。Number.toFixed() が期待どおりに丸められないことがあります。さらに調査した結果、64 番で丸めロジックが変更されていることが明らかになりました。これは、 MDN Number.toFixed() doc サイトで実行した例です。

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// expected output: "123.46"

console.log(financial(0.004));
// expected output: "0.00"

console.log(financial(0.005));
// expected output: "0.01"

console.log(financial(10.005));
// expected output: "10.01"

console.log(financial(63.005));
// expected output: "63.01" <<== This is still OK.

console.log(financial(64.005));
// expected output: "64.01" <<== THIS RETURNS 64.00, NOT 64.01. WHY?

console.log(financial(100.005));
// expected output: "100.01"  <<== THIS RETURNS 100.00, NOT 100.01. WHY?

console.log(financial(64.006));
// expected output: "64.01"  <<== This is OK as well

console.log(financial(64.015));
// expected output: "64.02"  <<== This is OK as well

console.log(financial(64.105));
// expected output: "64.11"  <<== This is OK as well

console.log(financial('1.23e+5'));
// expected output: "123000.00"

コード出力、および含まれていない他のいくつかのテストから、数値 64 およびそれ以上の数値で始まるように見えます。 (2)。toFixed(3) と 3 つの先行ゼロは試しませんでした。ただし、小数にゼロ以外の数字がある場合、丸めは正しく行われます。ただし、数値 64.006 は正しく 64.01 に丸められます。

この丸め動作は、私が理解できない何らかの理由で期待されていますか? これに対する回避策はありますか?

ありがとう。

4

0 に答える 0