This is what I am doing, which works 99.999% of the time:
((int)(customerBatch.Amount * 100.0)).ToString()
The Amount value is a double. I
You really should not be using a double value to represent currency, due to rounding errors such as this.
Instead you might consider using integral values to represent monetary amounts, so that they are represented exactly. To represent decimals you can use a similar trick of storing 580.55
as the value 58055
.
You could use decimal
values for accurate calculations. Double is floating point number which is not guaranteed to be precise during calculations.
no, multiplying does not introduce rounding errors but not all values can by represented by floating point numbers. x.55 is one of them )
My suggestion would be to store the value as the integer number of pennies and take dollars_part = pennies / 100
and cents_part = pennies % 100
. This will completely avoid rounding errors.
Edit: when I wrote this post, I did not see that you could not change the number format. The best answer is probably using the round method as others have suggested.
EDIT 2: As others have pointed out, it would be best to use some sort of fixed point decimal variable. This is better than my original solution because it would store the information about the location of the decimal point in the value where it belongs instead of in the code.
Try
((int)(Math.Round(customerBatch.Amount * 100.0))).ToString()
I'm guessing that 580.55 is getting converted to 58054.99999999999999999999999999..., in which case int will round it down to 58054. You may want to write your own function that converts your amount to a int with some sort of rounding or threshold to make this not happen.