Skip to content

Instantly share code, notes, and snippets.

@ateruimashin
Created December 16, 2021 07:11
Show Gist options
  • Save ateruimashin/cdb5598539b2687dd006f6a0f4f920ca to your computer and use it in GitHub Desktop.
Save ateruimashin/cdb5598539b2687dd006f6a0f4f920ca to your computer and use it in GitHub Desktop.
//小数の演算時の誤差を修正するために小数点の位置を探索するメソッド
//参考:https://qiita.com/k_moto/items/0b576a3351b77fb0aa98
function getDotPosition(value) {
//一度数値を文字列化
const strValue = String(value);
//小数点の位置の初期化
let dotPosition = 0;
//小数点の位置を取得(ない場合-1)
const whereDot = strValue.lastIndexOf('.');
//小数点が存在する時位置を取得
if (whereDot != -1) {
dotPosition = (strValue.length - 1) - whereDot;
}
//小数点の位置を返す
return dotPosition;
}
//加算(小数の計算の誤差を修正したもの)
function addValue(value1, value2) {
//それぞれの値の小数点の位置を取得
const dotPosition1 = getDotPosition(value1);
const dotPosition2 = getDotPosition(value2);
//小数点以下の位が大きい方の位置を取得
const maxPosition = Math.max(dotPosition1, dotPosition2);
//大きい方に小数の桁を合わせて文字列化し、小数点を除いて整数にする
const intValue1 = parseInt((value1.toFixed(maxPosition) + '').replace('.', ''));
const intValue2 = parseInt((value2.toFixed(maxPosition) + '').replace('.', ''));
//最後に割る値を計算
const div = Math.pow(10, maxPosition);
//整数値で足し算した後、10^Nで割る
return (intValue1 + intValue2) / div;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment