LoginSignup
0
0

More than 1 year has passed since last update.

JavaScriptで小数第二位までの足し算をする

Posted at

繰り返し足し算の中でハマる沼

JavaScriptでの小数の計算をググると計算後に100倍してMath.floorを利用し、最後に100で割る方法の紹介が多かった。
しかしこの場合、例えば1.8となるべき計算結果が179.99999...と計算された場合に1.79が答えになってしまう場合があり、足し算を繰り返していく処理の中で少しハマった。

シンプルな足し算

Math.roundを使う方がいいみたい。理由は上記のような場合でも四捨五入してくれるから。

let total = 0;
let numbers = [小数点以下がある数字の配列];
for (const num of numbers) {
    total = Math.round((total + num) * 100) / 100;
};

小数の係数が絡んでくるパターン

係数が小数の場合は係数に対してもMath.roundを使う。

let total = 0;
let numbers = [小数点以下がある数字の配列];
let coefficient = 0.61; //係数
for (const num of numbers) {
    total = Math.round((total + number * Math.round(coefficient)) * 100) / 100;
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0