Johan Herstad
Johan Herstad

Reputation: 692

How to display zero after the decimal on whole numbers?

I have a float that i want to display as 2.0 (or the entire float) But it always displays as 2 (without the decimals) when I use the float directly in razor. I have tried stuff like

float result = 2.0F;
float number = float.Parse(result.ToString("0.0"));
//or: (float)Math.Round(result, 1, MidpointRounding.ToEven);

But i can't seem to display results that have zero after the decimal as anything but whole numbers in html.

Why do I have to convert it to a string to be able to show it correctly in razor?

Upvotes: 0

Views: 1372

Answers (4)

tmaj
tmaj

Reputation: 35075

Here's a display of few of the many possible options.

public static void Main()
{
    var f = 2.0F;
    Print(f);

    f = 2.12345F;
    Print(f);
}

public static void Print(float f) {
    Console.WriteLine(f.ToString("0.0###"));
    Console.WriteLine(f.ToString("0.0"));
    Console.WriteLine(f.ToString("N1"));
    Console.WriteLine(f.ToString("G29"));
}

Output:

2.0
2.0
2.0
2
2.1235
2.1
2.1
2.12345004

Upvotes: 1

cancmrt
cancmrt

Reputation: 139

You can do that with formatting string.

float.ToString("0.0");

or

float.ToString("N1");

If you want more digits on display, you can increase Zero's after dot or you can change N1 value to N2

Example:

float.ToString("0.00");

or

float.ToString("N2");

Upvotes: 1

Joe
Joe

Reputation: 369

If your aim is to display it as a string then use:

float result = 2.0F;
string resultString = result.ToString("N1");

Upvotes: 0

Ahmed Msaouri
Ahmed Msaouri

Reputation: 316

Your code works, you are just converting the result to float back.

float result = 2.0F;
string numberstr = result.ToString("0.0");

or you can use:

float result = 2.0F;
Console.WriteLine(result .ToString("N1", CultureInfo.InvariantCulture));

Upvotes: 1

Related Questions