Reputation: 196689
I have a double
and I want to format it with the following rules:
So, as a few examples:
100 --> 100
99.958443534 --> 99.96
99.1 -> 99.10
Upvotes: 3
Views: 176
Reputation: 1952
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"
Upvotes: 1
Reputation: 50018
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);
Upvotes: 4
Reputation: 48567
You can use:
decimal a = 99.949999999M;
Math.Round(a, 2); // Returns 99.95
Upvotes: 0