280

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!

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Callum
  • 3,221
  • 3
  • 19
  • 18

9 Answers9

569

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

Michael
  • 3,982
  • 4
  • 30
  • 46
WraithNath
  • 17,658
  • 10
  • 55
  • 82
  • 61
    "N2" and "C2" will add thousand separators while "0.00" won't. – Marc K Jan 28 '14 at 13:08
  • 12
    Just in case you're unsure (I was), all of these ways for formatting a float value do provide rounding. – RenniePet Nov 12 '17 at 15:03
  • What about "00.00"? What's the point of having more than one 0 there like some people do have? – Marcos Pereira Feb 19 '21 at 14:38
  • 1
    @MarcosPereira It will pad the string with zeros. So 1.1 would turn into the string "01.10" and it would turn 22.2 into "22.20". This may be useful for sorting or something like that. – Brynn McCullagh Jul 08 '21 at 12:52
  • The "0.00" format works fine, but I can't find anything about it in the official documentation (linked above) or am I blind? – R1PFake Dec 27 '21 at 15:59
  • 1
    @R1PFake - There is some additional information in a Page that is linked from the URL I provided. You can read more here: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=net-6.0#System_Int32_ToString_System_String_ or here: https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring?view=net-6.0. Look for custom formatting. – WraithNath Dec 28 '21 at 21:09
55

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"
saastn
  • 5,717
  • 8
  • 47
  • 78
55

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.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
37

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.

Community
  • 1
  • 1
alexandrul
  • 12,856
  • 13
  • 72
  • 99
35

I believe:

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

Should do it.

See Link String Format Examples C#

aioobe
  • 413,195
  • 112
  • 811
  • 826
Bit
  • 1,068
  • 1
  • 11
  • 20
7

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
Jackson
  • 801
  • 10
  • 22
5

I like to use

$"{value:0.##}

It displays decimals optionally if there is some value.

Examples:

$"{50.255:0.##} //50,25
$"{50.2:0.##}   //50,2
$"{50.00:0.##}  //50
Skylin R
  • 2,111
  • 1
  • 20
  • 23
4
string outString= number.ToString("####0.00");
danyolgiax
  • 12,798
  • 10
  • 65
  • 116
  • 3
    There are different between "0" and "#" in custom format. "0": Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string. "#": Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string. [Reference](https://www.quora.com/How-do-I-format-floating-point-numbers-in-C) – 劉鎮瑲 Apr 12 '19 at 00:53
0
    private float LimitDecimalPlace(double number,int limitPlace)
    {
        float result = 0;
        string sNumber = number.ToString();
        int decimalIndex = sNumber.IndexOf(".");
        if (decimalIndex != -1)
        {
            sNumber = sNumber.Remove(decimalIndex + limitPlace + 1);
        }
       
        result = float.Parse(sNumber);
        return result;
    }
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 22 '22 at 23:37