JavaScriptで数値を小数点以下1文字に丸めることはできますか(正しく丸められます)?
私は* 10、丸め、/ 10を試しましたが、intの最後に小数点以下2桁が残っています。
Math.round(num * 10) / 10
作品、ここに例があります...
var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3
小数点以下1桁にしたい場合は、それが0になる場合でも、追加します...
var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!
// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros
// So, just make sure it is the last step before output,
// and use a number format during calculations!
参考のために、この原則を使用して、精度をとる便利な小さな丸い関数を次に示します...
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
... 使用法 ...
round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7
...デフォルトでは、最も近い整数に丸められます(精度0)...
round(12345.6789) // 12346
...そして、最も近い10または100などに丸めるために使用できます...
round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300
...負の数の正しい処理...
round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5
...そしてtoFixedと組み合わせて、一貫して文字列としてフォーマットできます...
round(456.7, 2).toFixed(2) // "456.70"
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加