1

I have some calculations on the client side with JavaScript.

var total = (((3 * 24) / 100) + 3); //result is 3.7199999999999998

I need to store this 3.7199999999999998 number in the database as it is. Database is on MySQL, i use Doctrine 2 for ORM, and entity has the precision set to /** @Column(type="decimal", precision=32, scale=16, nullable=false) * */, but after saving i see that in database is just the number 3.72, wtf ? After some checking i found that doctrine uses floatval and after executing this floatval(3.7199999999999998) you get 3.72!! why?

Is there a workaround for this ? like telling doctrine not to use the floatval and store the value as it is? also i dont want to use varchar for this column.

Thanks in advance!

Constantin
  • 2,288
  • 2
  • 24
  • 31

2 Answers2

2

3.72 is the correct value. The 3.7199999999999998 result is due to floating-point imprecision in JavaScript (See: How to deal with floating point number precision in JavaScript?). I'd suggest using toFixed() in your JavaScript code to avoid this.

var total = (((3 * 24) / 100) + 3).toFixed(2);
AlliterativeAlice
  • 11,841
  • 9
  • 52
  • 69
  • So because JavaScript is broken i should avoid 16 digits precision and to use only a precision of 2 digits ? And what to do if i need a higher precision ? – Constantin Jun 02 '15 at 20:54
  • If you need higher precision, use the [BigDecimal library for JavaScript](https://github.com/dtrebbien/BigDecimal.js) or [big.js](https://github.com/MikeMcl/big.js) – AlliterativeAlice Jun 02 '15 at 20:57
1

3.72 is actually the correct value. It would appear that JavaScript has a precision error when performing this calculation.

phuzi
  • 12,078
  • 3
  • 26
  • 50
  • Then how to get back `3.7199999999999998` number from `3.72` in JavaScript ? Because with this round up i get more errors using `3.72`. – Constantin Jun 02 '15 at 20:45
  • @Constantin Not sure why you want the incorrect value – phuzi Jun 02 '15 at 20:48
  • I need back this wrong number because i need to calculate back the percent later, and to be always the same. – Constantin Jun 02 '15 at 20:58
  • @Constantin - perhaps that should be included as part of the question. It sounds like there is more going on and there may be another solution. – phuzi Jun 02 '15 at 21:05