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?
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 ".
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 .
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).
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.
double
s and float
s 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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With