开发者

Converting Large Dollar Values in C#

开发者 https://www.devze.com 2023-04-10 02:45 出处:网络
I have an application that manages project costs from as little as a million to billions of dollars.Initially, users enter an estimate of the project: called an \'appropriation amount\'.

I have an application that manages project costs from as little as a million to billions of dollars. Initially, users enter an estimate of the project: called an 'appropriation amount'.

The Issue Is:

The original value is not converting as expected. Some examples include:

They enter-in: 111,222,333

It converts to: 111,222,336

They enter-in: 111,222,333,444

It converts to: 111,222,333,440

The Problem Occurrs Here:

The issue arises upon conversion in the following line of code...

project.AppropriationAmount = (!String.IsNullOrEmpty(txtAppropriationDollars.Text)) ? Convert.ToSingle(txtAppropriationDollars.Text) : 0;

NOTES:

project.AppropriationAmount is a fl开发者_运维技巧oat.

Thanks for the help!


You should use decimal instead of float for money.

From MSDN:

The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.

Using Convert.ToDecimal(..) and assigning to a decimal variable yielded the expected (correct) results for your examples.

0

精彩评论

暂无评论...
验证码 换一张
取 消