+ 1

Rounding SO small float values (0.00000000000001)

Hello, everyone Im trying to solve a problem my way (not good, i know, but just searching) and found another problem with rounding values. int discount = Convert.ToInt32(Console.ReadLine()); Dictionary<string, int> coffee = new Dictionary<string, int>(); coffee.Add("Americano", 50); coffee.Add("Latte", 70); coffee.Add("Flat White", 60); coffee.Add("Espresso", 60); coffee.Add("Cappucino", 80); coffee.Add("Mocha", 90); string[] s = coffee.Keys.ToArray(); int[] p = coffee.Values.ToArray(); for (int i = 0; i < p.Length; i++) { Console.WriteLine(s[i] + ": " + p[i] * (0.01 * (100 - discount))); } And I have 2 questions about that: 1) I have a dictionary here which have <string, int> types. So, why the result with float? It should be integer. 2) when I put "5" in "discount" variable it calculate : 60 * 0.95 = 57.00000000000001. I found the reason, but I cant understand how to fix exactly this problem. If I use "Ceiling" method, it is rounding this to 58 from 57. So how to fix this small float value to closest integer? Exactly this. Cause I need all another rounding to bigger one integer (i mean 66,5 to 67, 47.5 to 48... etc)

8th Feb 2022, 6:03 PM
Garegin
Garegin - avatar
5 Answers
0
You can use Math.Round(num) ; Math.Round(57.001) returns 57 Math.Round(47.8) returns 48
8th Feb 2022, 6:44 PM
Jayakrishna šŸ‡®šŸ‡³
0
I was trying that, but didnt get the way to solve this more procedurally. If I put 57.000000000001 exactly it will not solve same problem with other values
8th Feb 2022, 7:41 PM
Garegin
Garegin - avatar
0
for (int i = 0; i < p.Length; i++) { Console.WriteLine( s[i] + ": " + Math.Round( p[i] * (0.01 * (100 - discount))) ); } This way am telling, is this not solved your problem
10th Feb 2022, 1:22 PM
Jayakrishna šŸ‡®šŸ‡³
0
Its almost right, but it returns 66 (should return 67). Ive found that better use integer values in this formula, then it returns right result. But i cant understand, why it work like that. Results should be same. value - value * discount / 100 -------- it returns right result......
10th Feb 2022, 10:23 PM
Garegin
Garegin - avatar
0
There occurs a slite difference in fraction part value, when you do calculation with double values.. With integers, you always get the floored value.
11th Feb 2022, 8:46 PM
Jayakrishna šŸ‡®šŸ‡³