Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created February 25, 2019 20:57
Show Gist options
  • Save okovalov/11af907e7267faa62452cdaf50e5e26d to your computer and use it in GitHub Desktop.
Save okovalov/11af907e7267faa62452cdaf50e5e26d to your computer and use it in GitHub Desktop.
/**
* An idea how to address this 'issue'
* js> 0.1+0.2==0.3
* false
*
* The problem here is that number does not always equal to what is displayed
* js> (0.1).toPrecision(21)
* 0.100000000000000005551
* js> (0.2).toPrecision(21)
* 0.200000000000000011102
* js> (0.1+0.2).toPrecision(21)
* 0.300000000000000044409
*/
// Identify the minimum required precision
const precision = 8
const num1 = 0.1
const num2 = 0.2
const num3 = 0.3
// use setter and getter to 'format'/'cast' numbers acccordingly when saving and reading the values
console.log(
Number.parseFloat(
(
Number.parseFloat( (num1).toPrecision(precision) ) // a number
+
Number.parseFloat( (num2).toPrecision(precision) ) // another number
).toPrecision(precision)
)
===
Number.parseFloat( (num3).toPrecision(precision) ) // resulted number
) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment