Created
November 7, 2017 12:10
-
-
Save anonymous/0e5f8be4ee02374f339bd7d33563f3dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 少数第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