Formatting a float to 2 decimal places

C#VariablesFloating PointDecimal

C# Problem Overview


I am currently building a sales module for a clients website. So far I have got the sale price to calculate perfectly but where I have come stuck is formatting the output to 2 decimal places.

I am currently calling this in a variable so that I can data bind the results to a listview.

Sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())),

Can anyone show me how to format the output to 2 decimal places?? Many Thanks!

C# Solutions


Solution 1 - C#

You can pass the format in to the ToString method, e.g.:

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

Standard Number Format Strings

Solution 2 - C#

The first thing you need to do is use the decimal type instead of float for the prices. Using float is absolutely unacceptable for that because it cannot accurately represent most decimal fractions.

Once you have done that, Decimal.Round() can be used to round to 2 places.

Solution 3 - C#

String.Format("{0:#,###.##}", value)

A more complex example from String Formatting in C#:

> String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value); > > This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

Solution 4 - C#

I believe:

String.Format("{0:0.00}",Sale);

Should do it.

See Link String Format Examples C#

Solution 5 - C#

This is for cases that you want to use interpolated strings. I'm actually posting this because I'm tired of trial and error and eventually scrolling through tons of docs every time I need to format some scalar.

$"{1234.5678:0.00}"        "1234.57"        2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}"     "   1234.57"     right-aligned
$"{1234.5678,-10:0.00}"    "1234.57   "     left-aligned
$"{1234.5678:0.#####}"     "1234.5678"      5 optional digits after the decimal point
$"{1234.5678:0.00000}"     "1234.56780"     5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}"    "01234.57"       5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}"           "1235"           as integer, notice that value is rounded
$"{1234.5678:F2}"          "1234.57"        standard fixed-point
$"{1234.5678:F5}"          "1234.56780"     5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}"          "1.2e+03"        standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}"          "1.2E+03"        standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}"          "1.23E+03"       standard general with 3 meaningful digits
$"{1234.5678:G5}"          "1234.6"         standard general with 5 meaningful digits
$"{1234.5678:e2}"          "1.23e+003"      standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}"          "1.235E+003"     standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}"          "1,234.57"       standard numeric, notice the comma
$"{1234.5678:C2}"          "$1,234.57"      standard currency, notice the dollar sign
$"{1234.5678:P2}"          "123,456.78 %"   standard percent, notice that value is multiplied by 100
$"{1234.5678:2}"           "2"              :)

Performance Warning

Interpolated strings are slow. In my experience this is the order (fast to slow):

  1. value.ToString(format)+" blah blah"
  2. string.Format("{0:format} blah blah", value)
  3. $"{value:format} blah blah"

Solution 6 - C#

As already mentioned, you will need to use a formatted result; which is all done through the Write(), WriteLine(), Format(), and ToString() methods.

What has not been mentioned is the Fixed-point Format which allows for a specified number of decimal places. It uses an 'F' and the number following the 'F' is the number of decimal places outputted, as shown in the examples.

Console.WriteLine("{0:F2}", 12);    // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3);  // 12 - ommiting fractions

Solution 7 - C#

string outString= number.ToString("####0.00");

Solution 8 - C#

I like to use

$"{value:0.##}

It displays two decimals only if there is some value at those places.

Examples:

$"{50.255:0.##} //50,25
$"{50.2:0.##}   //50,2
$"{50.00:0.##}  //50

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCallumView Question on Stackoverflow
Solution 1 - C#WraithNathView Answer on Stackoverflow
Solution 2 - C#Michael BorgwardtView Answer on Stackoverflow
Solution 3 - C#alexandrulView Answer on Stackoverflow
Solution 4 - C#BitView Answer on Stackoverflow
Solution 5 - C#saastnView Answer on Stackoverflow
Solution 6 - C#JacksonView Answer on Stackoverflow
Solution 7 - C#danyolgiaxView Answer on Stackoverflow
Solution 8 - C#Skylin RView Answer on Stackoverflow