JavaScriptプログラムに関する各種メモ書き

JavaScript で正しく小数点計算を行う

● JavaScript で正しく小数点計算を行う

浮動小数点では正しく小数点計算ができないのでライブラリを利用します。以下の3択で容量の小さい順に

  • big.js
  • bignumber.js
  • decimal.js
  • decimal.js-light (decimal.jsの軽量版)

です。 作者は同じなので使い方はどれも同じです。

decimal.js-light を使ってみましょう。

1. decimal.min.js を読み込む

<script src="https://cdn.jsdelivr.net/npm/decimal.js-light@2.5.1/decimal.min.js"></script>

2. 小数点計算を行う

var total = new Decimal( 1.5749 );
var d = new Decimal( 2.75 );

console.log( total.plus(d) );
console.log( total.minus(d) );
console.log( total.times(5) );

などなど、

3. メソッド一覧

absoluteValue
comparedTo
decimalPlaces
dividedBy
dividedToIntegerBy
equals
exponent
greaterThan
greaterThanOrEqualTo
isInteger
isNegative
isPositive
isZero
lessThan
lessThanOrEqualTo
logarithm
minus
modulo
naturalExponential
naturalLogarithm
negated
plus
precision
squareRoot
times
toDecimalPlaces
toExponential
toFixed
toInteger
toJSON
toNumber
toPower
toPrecision
toSignificantDigits
toString
valueOf

http://mikemcl.github.io/decimal.js-light/

No.1808
11/17 16:54

edit