Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding of float values

I have the double value like 12.256852651 and I want to display it as 12.257 as a float number without converting it in to a string type.

How can I do it in C# ?

like image 292
Dharmesh Avatar asked Nov 23 '11 09:11

Dharmesh


People also ask

How do you round a float value?

The round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals. The default number of decimals is 0, meaning that the function will return the nearest integer.

Do floats round up or down?

Bookmark this question. Show activity on this post.

Does 0.5 get rounded up or down?

0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number.


2 Answers

I'd first convert to Decimal and then use Math.Round on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.

Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero) 

You should also look into the choice of MidpointRounding, since by default this uses Banker's round, which is not what you are used to from school.

like image 84
CodesInChaos Avatar answered Sep 27 '22 19:09

CodesInChaos


If you want to display it, it will be a string and that's what you need to use.

If you want to round in order to use it later in calculations, use Math.Round((decimal)myDouble, 3).

If you don't intend to use it in calculation but need to display it, use double.ToString("F3").

like image 44
Oded Avatar answered Sep 27 '22 19:09

Oded