Floating-point cheat sheet for JavaScript
Floating-Point Types
JavaScript is dynamically typed and will often convert implicitly between strings and floating-point numbers (which are IEEE 64 bit values). To force a variable to floating-point, use the global parseFloat()
function.
var num = parseFloat("3.5");
Decimal Types
The oldest decimal type for JavaScript seems to be a port of Java’s BigDecimal
class, which also supports rounding modes:
var a = new BigDecimal("0.01");
var b = new BigDecimal("0.02");
var c = a.add(b); // 0.03
var d = c.setScale(1, BigDecimal.prototype.ROUND_HALF_UP);
There is also bignumber.js
, which is smaller and faster:
BigNumber.config({ROUNDING_MODE: BigNumber.ROUND_HALF_UP})
var a = new BigNumber("0.01");
var b = new BigNumber("0.02");
var c = a.plus(b); // BigNumber(0.03)
var d = c.toFixed(1); // "0.0"
How to Round
var num = 5.123456;
num.toPrecision(1) //returns 5 as string
num.toPrecision(2) //returns 5.1 as string
num.toPrecision(4) //returns 5.123 as string
Using a specific rounding mode:
new BigDecimal("1.25").setScale(1, BigDecimal.prototype.ROUND_HALF_UP);
Resources
© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)