-1

Hello I have problem with a simple function in JavaScript if I add 0.0001 + 0.0001 + 0.0001 i have 0.0002999999999999999999 I don't know why because it's simple Number(x) + Number(y).

With php I use this function and it's work perfectly

$number = number_format($number, 10, '.', '');
$number = rtrim(rtrim($number, '0'), '.');

What is the equivalent of this script PHP in Javascript?

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
p4c
  • 153
  • 2
  • 12

4 Answers4

2

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.0001 + 0.0001).toFixed(12) // 0.0002

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.0001 + 0.0001) * 1e12) / 1e12
Amitesh Yadav
  • 202
  • 1
  • 10
1

You're running into errors with floating point storage of numbers which isn't perfect. If you know exactly what precision you need, you can use the toFixed function to display the number as a string:

var x = 0.0001 + 0.0001 + 0.0001;
console.log(x.toFixed(4));
// "0.0003"
Samuel Littley
  • 724
  • 7
  • 17
1

Try like this using toFixed():

var x = 0.0001 + 0.0001 + 0.0001;
alert(x.toFixed(4));

JSFIDDLE DEMO

Also note that Javascript uses 64 bit floating point representation and follow IEEE 754 standard for float.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You may take help of toFixed to convert it to string and then convert it back to a number.

+(0.0001 + 0.0001).toFixed(12) // 0.0002

In case of IE you may write like this

Math.round((0.0001 + 0.0001) * 1e12) / 1e12
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
Shayan Ghosh
  • 882
  • 6
  • 14