简体   繁体   中英

C# decimal checking doesn't work properly

So i tried this code bellow to check for decimal spaces because I can only use Ifs (If you have a suggestion how to check for decimals with only Ifs that would be appriciated.)

double amount = double.Parse(Console.ReadLine());
cents5 = amount / 0.05;
if (cents5 - (int)cents5 == 0)
{
    Console.WriteLine(cents5 + " * 5 cents");
}

Console.WriteLine(cents5 + "  " + (int)cents5);

But when i for example try to put in 150.10 for the amount the console returns the value 3002 for the result5c and the value 3001 for (int)result5c. It works for other values nicely idk why I doesn't work here.

I'm sorry if the code doesn't look nice but I try :(. Feedback though is appriciated :D

The problem is that double isn't a precise data structure and can easily result in rounding errors, if you want to get the Raw value of the double you can use the

Console.WriteLine(cents5.ToString("R"));

This will print

3001.9999999999995

If this double value now gets casted to int it will just truncate the fraction and only return

3001

There are several solutions you can pick

  1. use a data type that has an higher precision for floating values like decimal

     decimal amount = decimal.Parse(Console.ReadLine()); decimal cents5 = amount / 0.05m; //<-- use m after 0.05 to mark it as decimal literal if (cents5 - (int)cents5 == 0) { Console.WriteLine(cents5 + " * 5 cents"); } Console.WriteLine(cents5 + " " + (int)cents5); 
  2. instead of the cast to int use Convert.ToInt32

     double amount = double.Parse(Console.ReadLine()); double cents5 = amount / 0.05; if (cents5 - Convert.ToInt32(cents5) == 0) { Console.WriteLine(cents5 + " * 5 cents"); } Console.WriteLine(cents5 + " " + Convert.ToInt32(cents5)); 
  3. Round the wrong precision of your double value

     double amount = double.Parse(Console.ReadLine()); double cents5 = Math.Round(amount / 0.05, 2); if (cents5 - (int)cents5 == 0) { Console.WriteLine(cents5 + " * 5 cents"); } Console.WriteLine(cents5 + " " + (int)cents5); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM