Skip to content
Arthur Guiot edited this page Jul 29, 2017 · 1 revision

Original concept

The $.math object comes from devrafalko/exact-math project (don't worry, I asked him if I could include his project in DisplayJS.

Description

How does it work?

All numbers in JavaScript are stored as 64-bits Floating point numbers. JavaScript has difficulties with precise floating point values.

Code Result
var result = 0.1 + 0.2; 0.30000000000000004
var result = 0.4 * 0.2 0.08000000000000002
var result = 0.45 - 0.15; 0.30000000000000004
var result = .82 / 10; 0.08199999999999999
What can I use $.math for?
  • you can do simple multipication, division, subtraction and addition arithmetic calculations and get precise results.
  • you can use $.math to compare two results in if()` condition.
  • you can use $.math results as output values displayed for the users. (prevent 0.30000000000000004)

Browser Support

Chrome Firefox IE Safari Opera
yes yes yes yes yes

Methods

name description syntax parameters description return value
add $.math.add() adds values passed as arguments. $.math.add(arg1,arg2,...) You can set any number, but at least two, arguments of Number type, separated by comma. Don't use arithmetic signs between arguments. The result of addition operation.
sub $.math.sub() subtracts values passed as arguments (from left to righ). $.math.sub(arg1,arg2,...) You can set any number, but at least two, arguments of Number type, separated by comma. Don't use arithmetic signs between arguments. The result of subtraction operation.
mul $.math.mul() multiplies values passed as arguments. $.math.mul(arg1,arg2,...) You can set any number, but at least two, arguments of Number type, separated by comma. Don't use arithmetic signs between arguments. The result of multiplication operation.
div $.math.div() divides values passed as arguments (from left to righ). $.math.div(arg1,arg2,...) You can set any number, but at least two, arguments of Number type, separated by comma. Don't use arithmetic signs between arguments. The result of division operation.

Syntax

var mul = $.math.mul(.1, .2, .5, .7);  //0.007
var sub = $.math.sub(10, 0.5, 2, 3);    //4.5

var arr = [.1, .2, .4, .05, 7];
var fun = function(i){return arr[i]};
var add = $.math().add(arr[1], fun(2), 5.3);    //5.9

var a = $.math.add(5, 3);
var b = $.math.sub(9, 1);
var c = $.math.mul(a, b, exactMath.div(10, 2));   //320

var d = 34e-5;
var e = .1254e+3;
var f = $.math.mul(d, e);    //0.042636

⚠️ Questions?

Don't hesitate to ask your questions ⁉️ in the issue part 😁

Clone this wiki locally