Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a float value in c#?

I have a problem rounding a float value. I have a float value that is set 0.8 but in the c# code it is somehow 0.80000000000000004.

So i want to round it so it becomes 0.8.

i have tried:

float roundedFloatvalue = (float)Math.Round((Decimal)floatvalue, 2, MidpointRounding.AwayFromZero);

and:

float roundedFloatvalue = Truncate(floatvalue, 2);

public static float Truncate(float value, int digits)
{
    double mult = Math.Pow(10.0, digits);
    double result = Math.Truncate(mult * value) / mult;
    return (float)result;
}

It just seems that i cant get 0.80000000000000004 to be 0.8 and i dont know why any of the above doesnt work.

like image 737
Diemauerdk Avatar asked Jan 07 '14 09:01

Diemauerdk


People also ask

How do you round a float to two decimal places?

This is a two step process: Multiply the number by 100 and round the result down to the nearest integer. Divide the result by 100 to round down the float to 2 decimal places.

Can you round up in C?

In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).

What is 2f in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

What is float rounding?

In floating point arithmetic, two extra bits are used to the far right of the significand, called the guard and round bits. At the end of the arithmetic calculation, these bits are rounded off. We always round towards the closer digit (i.e. 0.00-‐0.49 → 0 and 0.51-‐0.99 → 1).


1 Answers

You cannot express 0.8 exactly as a binary floating point value since 0.8 is not representable in binary floating point. Required reading on this topic is What Every Computer Scientist Should Know About Floating-Point Arithmetic.

You might use decimal instead, which represents numbers using decimal floating point and can represent 0.8 exactly. Or you might choose to continue using binary floating point, but only display limited numbers of digits after the decimal point.

To get the value into a decimal variable, rounded to two decimal places, you write:

decimal decimalValue = Math.Round((decimal)floatValue, 2);
like image 60
David Heffernan Avatar answered Sep 22 '22 12:09

David Heffernan