Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding up c# giving wrong answer

I am programming a stocks/production program for a school project (bike factory) and I have to round some numbers up such as the bikes that have to be produced (due to fallout it are doubles).

If I use the following code:

double test = Math.Ceiling(100 * 1.09);

label75.Text = Convert.ToString(test);

I get as an answer 110, but that's not right, it should be 109 (9% of 100). Although it seems to work with values below 9%.

What am I doing wrong?

like image 990
Ben Non Avatar asked Sep 11 '13 20:09

Ben Non


People also ask

How do I round numbers in C?

round() function in c is used to return the nearest integer value of the float/double/long double argument passed to this function. If the decimal value is from ". 1 to . 5", it returns an integer value which is less than the argument we passed and if the decimal value is from ".

Does C round up or down int?

Integer division truncates in C, yes. (i.e. it's round towards zero, not round down.) round toward 0 meaning . 5 or greater => round up 0 to .

Do ints round down in C?

In the C Programming Language, the floor function returns the largest integer that is smaller than or equal to x (ie: rounds downs the nearest integer).

What is a float C?

Float is a datatype which is used to represent the floating point numbers. It is a 32-bit IEEE 754 single precision floating point number ( 1-bit for the sign, 8-bit for exponent, 23*-bit for the value. It has 6 decimal digits of precision.


2 Answers

doubles and floats are binary floating point types. This means they cannot precisely represent many decimal numbers (like 1.09). This leads to some subtle round off errors. In your case 100 * 1.09 actually results in a number very slightly larger than 109, so the Ceiling function correctly rounds it up to the nearest integer, 110.

Change it to a decimal and you'll get the result you expect:

decimal test = Math.Ceiling(100 * 1.09m); // 109

Note the m in 1.09m identifies it as a decimal literal. This works because the decimal type is specifically designed to represent decimal numbers (rather than just their binary approximations, as double and float do).

like image 168
p.s.w.g Avatar answered Oct 10 '22 06:10

p.s.w.g


Floating point arithmetic is not in base 10, it's in base 2. the double type doesn't have an exact base-2 equivalent of 1.09

To illustrate, if you put a break-point at the end of the following program

public static void Main()
{

    double test = 100 * 1.09;
}

than test would show up as 109.00000000000001

like image 7
Sam I am says Reinstate Monica Avatar answered Oct 10 '22 05:10

Sam I am says Reinstate Monica