Keep zero after the comma using float type?

4

I have a database where product values are stored.

When zero numbers occur after the commas they come with zero.

I did a test and with decimal it worked, but my application uses float , so I need to work with float .

decimal numero = decimal.Parse("50,00");
string resultado = numero.ToString();
Console.Write(resultado); /* Resultado: 50,00 */

I'm using a float that allows for nulls:

float? numero = null;
    
asked by anonymous 03.02.2014 / 18:08

3 answers

5

Simple, use ToString :

resultado.ToString("N2");

Where 2 is the number of decimal places.

Reference

    
03.02.2014 / 18:13
2

If the problem is to display this value without the zero after the comma then you can try to use the String format to display the way you want it:

float valor = 1.00f;

Console.WriteLine(valor); // 1
Console.WriteLine(valor.ToString("0.00")); // 1,00
    
03.02.2014 / 18:16
0

Short answer: never use float ;-)

Long answer: float is not able to keep the number exactly as you describe it. Try doing this in the Chrome console, for example:

0.1 * 0.2

The answer will be     0.020000000000000004

Because there are float failures in how the number is put into memory and then 0.02 is not stored exactly this way.

If you perform calculations on these numbers, ALWAYS use DECIMAL (and in SQL, NUMBER (X, Y), where X is the total number of digits and Y is the number after the decimal point).

Any other use with single or double will cause rounding problems (something that even Excel has problems).

Single or float are quick to do other things like graphics, DirectX, etc ... but for calculations, especially monetary, never use them.

    
03.02.2014 / 18:16