Reputation: 317
I have below code :
private string Do2Decimal(string value)
{
return String.Format("{0:0.##}", value);
}
Here I am passing string value as 16.32222.
What I know is, above code should format my value to 16.32.
But it is showing output value as 16.32222.
What mistake I am doing here??
Update :
I have values in string format that is : "16.32222".
Sorry forgot to mention before.
Upvotes: 2
Views: 4913
Reputation: 223282
Because you are passing it a string value. The formatting would work for floating point numbers / decimals. Just parse the number to either decimal / double type depending on your requirement like:
String.Format("{0:0.##}", decimal.Parse(value));
You can also use decimal.TryParse
(or TryParse) family method for safer parsing. You can also modify your method to receive decimal/double type parameter and then apply the formatting. It would convey a better intent, IMO.
If your string has .
as NumberDecimalSeparator and your culture doesn't support .
as NumberDecimalSeparator then you can pass CultureInfo.InvariantCulture
while parsing like:
string value = "16.322222";
string formattedString = String.Format("{0:0.##}", decimal.Parse(value, CultureInfo.InvariantCulture));
Upvotes: 20
Reputation: 707
Try this
String.Format("{0:0.00}", decimal.Parse(value));
to get two degit value after point.
Upvotes: -2