Reputation: 3
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
Upvotes: 0
Views: 435
Reputation: 7440
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
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);
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));
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);
Upvotes: 1