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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With