Round numbers in C # being the decimal place 0 or 5

Posted on

Question :

I need to round numbers in such a way that they have only one decimal place worth 0 or 5.

For example

``````1 -> 1
1.1 -> 1.5
1.4 -> 1.5
1.5 -> 1.5
1.6 -> 2
2 -> 2
``````

Does anyone know of a simple way to do this?

Given the specificity of the rule, I suggest separating the whole integer from the fractional part and – as desired – add `0.5` , `1` or nothing:

``````int y = (int)x; // Descarta a parte decimal, arredondando pra baixo
if ( 0 < x - y && x - y <= 0.5 ) // Se a parte decimal for não-nula e menor ou igual a 0.5
x = y + 0.5;                 // acrescenta 0.5 à parte inteira
else if ( 0.5 < x - y ) // Se a parte decimal for não-nula e maior a 0.5
x = y + 1;          // arredonda pro próximo inteiro
``````

To do this type of rounding, assuming its value is in a `float` variable called `x` , you can do the following:

``````x = (float)((int)((x + 0.4f) * 2.0f)) * 0.5f;
``````

If it is `double` :

``````x = (double)((int)((x + 0.4) * 2.0)) * 0.5;
``````

To round more homes, such as 1.51 to 2, you can use `0.49f` (or `0.49` ) instead of `0.4f` .

The more houses needed, the more 9’s would be needed after `0.4` .

I decided to answer because there are problems in the other answers. They are not wrong, there is a better solution. They do not contemplate negatives and there are performance problems, although this is not very relevant. One is an ugly solution and the other is unnecessarily complicated. I hope I have not created any other problems in mine.

I’d start by doing something simple and elegant:

``````Ceiling(value * 2) / 2
``````

This solution does not solve the problem of negative numbers, it just shows how it can be simplified. The solution of the negatives does not make it much more complicated.

Complete solution

For types `Decimal` and `double` . If you need it, it’s very easy to create for `float` . Note that I’m using the Roslyn compiler (C # 6, see more information at