Multiplying a double value by 100.0 introduces rounding errors?

前端 未结 8 1050
后悔当初
后悔当初 2020-12-19 07:22

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

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-19 07:59

    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.

提交回复
热议问题