I have a double
and I want to format it with the following rules:
- If there are no decimal places show just the number (see 100 example below)
- If there are any decimal places show 2 de开发者_如何学Gocimal places
So, as a few examples:
100 --> 100
99.958443534 --> 99.96
99.1 -> 99.10
You could check if its a whole number, the use the type of formatting based on that:
string res = string.Format(((number % 1) == 0) ? "{0:0}" : "{0:0.00}", number);
What about:
var a = 100;
var b = 99.95844354;
var aAnswer = a.ToString("0.##"); //aAnswer is "100"
var bAnswer = b.ToString("0.##"); //bAnswer is "99.96"
You can use:
decimal a = 99.949999999M;
Math.Round(a, 2); // Returns 99.95
精彩评论