Keep zero after comma using the float type?

Asked

Viewed 5,030 times

4

I have a database where product values are stored.

When there is occurrence of numbers with zero after commas they come without zero.

I did a test and with decimal it worked, but my application uses the type float, then I need to make it 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 nulls:

float? numero = null;
  • The result of your code is 5000 for me. Decimal.Parse seems to ignore commas. Also decimal types do not store the amount of zeros to the right of the original number, but you can force a specific amount by formatting as a string again.

3 answers

5


Simple, use ToString:

resultado.ToString("N2");

Where 2 is the number of decimal places.

Reference

  • 1

    It worked, as my float is a Nullable I just had to add the parameter value: resultado.Value.ToString("N2");, thank you.

  • Yes, in the case of Nullables is a good practice to check if it has a value before using it with HasValue or GetValueOrDefault.

2

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

float valor = 1.00f;

Console.WriteLine(valor); // 1
Console.WriteLine(valor.ToString("0.00")); // 1,00

0

Short answer: never use float ;-)

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

0.1 * 0.2

The answer will be 0.020000000000000004

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

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

Any other use with single or double will bring you 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.

  • Rounding is quite acceptable when the accuracy of the result is not important, just the magnitude. Avoid generalizing like this. For monetary calculations the ideal is to use a fixed point (count cents instead of real for example). Additionally, this answer does not answer what was asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.