Callum
Callum

Reputation: 3381

Formatting a float to 2 decimal places

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!

Upvotes: 295

Views: 646977

Answers (10)

Skylin R
Skylin R

Reputation: 2271

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

Upvotes: 8

aftamat4ik
aftamat4ik

Reputation: 718

there is two ways of handling this problem

  1. if we want to print .00 at the end of the number
value.ToString("0.00") // show only two digits of float value after dot
// for 2.145 will give "2,14" and for 2 will give "2.00"
  1. if we don't want to print any numbers if float is whole
value.ToString("0.##") // show only two digits of float value after dot
for 2.145 will give "2,14" and for 2 will give "2" without float part

Upvotes: 0

Priyanshu Dubey
Priyanshu Dubey

Reputation: 1

    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;
    }

Upvotes: 0

Bit
Bit

Reputation: 1078

I believe:

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

Should do it.

See Link String Format Examples C#

Upvotes: 35

saastn
saastn

Reputation: 6015

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"

Upvotes: 68

Jackson
Jackson

Reputation: 911

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

Upvotes: 7

WraithNath
WraithNath

Reputation: 18013

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

Upvotes: 586

alexandrul
alexandrul

Reputation: 13246

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.

Upvotes: 37

Michael Borgwardt
Michael Borgwardt

Reputation: 346300

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.

Upvotes: 55

danyolgiax
danyolgiax

Reputation: 13086

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

Upvotes: 4

Related Questions