0

So, I have an object.

var position = {
  x: 1,
  y: 0
}

After few operations x or y can become something like 0.3700000000000001. However, I need it to be 0.37. I tried:

position[x].toFixed(2)

What is the right way to get get rid of 00000000000001 ?

Max Popov
  • 347
  • 5
  • 15
  • 2
    What is problem using `toFixed()`? – Maheer Ali Apr 17 '19 at 14:29
  • 3
    You maybe need to do **position[x]=position[x].toFixed(2)** – nacho Apr 17 '19 at 14:32
  • I think that you can find an answer in this question which is very similar to yours: https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary In aswer given by [A Kunin](https://stackoverflow.com/users/1736537/a-kunin ) you will find possible options and some cases when vaules can be wrong. – iwokal Apr 17 '19 at 14:34

4 Answers4

0

There should not be any problem except using the string key or dot notation:

var position = {
  x: 0.3700000000000001,
  y: 0
}
position.x = +position.x.toFixed(2); // + converts the resulted string to number
console.log(position.x);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

position[x] will get property of the position object which will be equal to value variable x. You should use position.x.

And you also need to change the value of position.x because position.x.toFixed(2) will not change the value.

position.x = position.x.toFixed(2)

toFixed() returns a string. You should convert it to float again using +.

console.log(+(0.3700000000000001). toFixed(2))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • This don't work, because `(+(0.3700000000000001). toFixed(2))` is `"0.369999999999999996"` and not `0.37`; `(+(0.3700000000000001). toFixed(2)).toPrecision(18)`shows it. – Wiimm Apr 18 '19 at 13:46
0

If you want a number, there is no way to drop 00000000000001 to get 0.37 exactly. Like for other languages (most hardware supports IEEE 754), the number 0.37 does not exists. If scanning 0.37 it is rounded to the nearest possible number: 0.37.toPrecision(18) shows "0.369999999999999996".

Because of this, toFixed() returns a string and not a number. So it is nonsense to use toFixed() and convert the result back to a float.

The easiest solution is to live with these unexact values and use toFixed() for output only (that is the idea of toFixed()).

Another solution for e.g. money is, to store all values as cent/penny and divide the values by 100 only on output: ($cent/100).toFixed(2)

Wiimm
  • 2,971
  • 1
  • 15
  • 25
-1

You are getting the value but you are not storing it, so the original vulea is not changed. You need to do:

var position = {
  x: 1,
  y: 0
}

position.x=position.x.toFixed(2)
nacho
  • 5,280
  • 2
  • 25
  • 34