D
D
Dmitry Sergeev2011-09-12 11:07:38
JavaScript
Dmitry Sergeev, 2011-09-12 11:07:38

Javascript: 0.03x30.00 = 0.899999. Why? And what is the correct way to multiply these numbers?

x = 0.03*30.00;
alert(x); // 0.89999999


just in case: windows xp, firefox 6

Answer the question

In order to leave comments, you need to log in

6 answer(s)
Y
YasonBy, 2011-09-12
@JetMaster

Read until enlightenment: " What you need to know about floating point arithmetic ."

D
Dmitry Sergeev, 2011-09-12
@JetMaster

found a crutch on stackoverflow

function multFloats(a,b){
  var atens = Math.pow(10,String(a).length - String(a).indexOf('.') - 1), 
      btens = Math.pow(10,String(b).length - String(b).indexOf('.') - 1); 
  var result = (a * atens) * (b * btens) / (atens * btens); 
  return result;
}

K
korvindest, 2011-09-12
@korvindest

This is due to a floating point calculation error.
To avoid this, you can first carry out all calculations with integers, and then divide to the desired order.
For example: x = (3*30.00)/100; alert(x);

G
gaelpa, 2011-09-12
@gaelpa

If you need to work specifically with rational fractions, then you can find a suitable library for this matter. I found this , if someone points out a more developed and popular one, I will be grateful.

E
Eldar Musin, 2011-09-12
@eldarmusin

Looking at how important these calculations are.
If this is for drawing statistics, building charts, then you can simply round for example - The easiest way.
Or, as mentioned above, build a function that will calculate step by step each operation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question