How to Format a Float to 2 Decimal Places
When working with floating-point numbers in programming, it's often necessary to format them with a specific number of decimal places for presentation. For example, in a sales module, you may want to display sale prices with 2 decimal places.
To format a float to 2 decimal places, the ToString method can be used with a format string. The format string specifies the desired format of the output.
For example, the following code formats a float variable to 2 decimal places:
float sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())); sale.ToString("0.00"); // 2 decimal places
The "0.00" format string specifies that the output should have 2 decimal places. Other commonly used format strings include:
Here are some examples of how these format strings would apply to a float value of 123.456:
Format String | Output |
---|---|
"0.00" | 123.46 |
"n2" | 123,46 |
"c2" | 3.46 |
When data binding the results to a listview, the formatted string can be used to display the sale price.
The above is the detailed content of How to Format a Float to Two Decimal Places in C#?. For more information, please follow other related articles on the PHP Chinese website!