Chiwa wrote:
Hey,
Expression:
Math.floor(x * 100) / 100
x= 4.1 gives 4.09, why in gods name?
While other values for x don't give a problem.
Thx in advance
Chiwa
Just so you know, this is not just a limitation of Javascript. Many
other languages (C/C++ for instance) have this as an issue. That is
because Real numbers (floating point numbers) are _ALWAYS_
approximations. When you do a measurement of your finger (for
instance), and you measure exactly 1.25 inches... is that really
correct? Or could it be 1.2500000234358 9 inches instead? Or
1.2500000034322 349872342229? (You get the idea)
For this reason (and others dealing with the complexity of floating
point numbers), when a float (indescrete) is represented by binary data
(descrete), you will have some goofiness... it is guaranteed.
Because of this, most languages have methods for you to set the
precision (the number of significant figures), where rounding will occur
to the precision value you wish for.
If you desire an exact floating point value, such as in something like
money calculations, simply set your precisions.
You can also work in values multiplied by (10*order)... For instance,
$10.47 can be worked with as integers... immagine 1,047 pennies :) You
can convert it back by dividing or modding by (10*order) in integer form.
I have had to use that method once when developing assembly code on an
8-bit processor. There was no float support, so I needed to work in
values multiplied by (10*order), and then do some simple calculations to
provide useful user information.
Blah.... I wrote too much. Oh well, I hope it helps :)
Brian