Adding decimals at 2 points equals a magically long decimal?!?

3 posts

Flag Post

When two decimals go through an operation, on occasion it results in some magically long decimal.

I have a lengthy solution, however I’d like to know if there’s anything better I could do before I dive in and make a lengthy/messy implementation.

EXAMpLE.
a:Number = Math.floor(Math.random()*100)/100; //.33
c:Number = 19.45
c += a
trace © //returns 19.780000000002.

SOLUTION.
var a:Number; //we want to keep this number in case of multiple operations
var b:int; //used to round trailing numbers
var c:Number; //used for operations between ‘a’ and this
a = BID; //BID is a positive number with a decimal
c = LOOT; //LOOT is a positive number with a decimal
c += a; //the magical operation, that results with the long decimal.
b = c*100; //‘b’ is an int which will round off the magical trailing decimals
c = b/100; //is our result back in decimal form, without the magical decimals
LOOT = c; //The resulting correct dollar decimal form used for display.

I’m not looking so much for code or a function with the same results, rather, I’d like to know why this is happening and if there is a better way to work with dollars and cents in a game without storing it as an int *100.

 
Flag Post

You have discovered floating point error

 
Flag Post

I feel like I just got an achievement.