Formatting a float to 2 decimal places

Callum picture Callum · Jun 15, 2011 · Viewed 427.6k times · Source

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!

Answer

WraithNath picture WraithNath · Jun 15, 2011

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