Skip to content

Instantly share code, notes, and snippets.

Created November 7, 2017 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/0e5f8be4ee02374f339bd7d33563f3dc to your computer and use it in GitHub Desktop.
Save anonymous/0e5f8be4ee02374f339bd7d33563f3dc to your computer and use it in GitHub Desktop.
// 少数第3位で四捨五入して、1.01にしたい。
var value = 1.005;
// ダメな例
var ngValue = Math.round(value * 100) / 100;
console.log(ngValue); // ⇛ 1 になる
// 解決策(1) 外部ライブラリを用いる
var BigNumber = require('bignumber.js');
var bnValue = new BigNumber(1.005);
var okValue1 = bnValue.round(2).toNumber();
console.log(okValue1); // ⇛ 1.01 になる
// 解決策(2) 文字列に変換してから四捨五入する。
var strValue = value.toFixed(3); // ⇛ "1.005"
strValue = strValue.replace('.', ''); // ⇛ "1005"
var okValue2 = strValue.toNumber(); // ⇛ 1005
okValue2 = Math.round(okValue / 10) / 100; // ⇛ 1.01
console.log(okValue2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment