Reputation: 624
I want to format my double
values limiting to 2 significant places, but not in integer part of the number.
Currently I use G2
notation, but it displays number in scientific notation if integer part contains more than 2 places.
Also I tried 0.##
, but it keeps 2 significant places in the fractional part no matter how many are there in the integer one.
What I want is this:
1234 => 1234
123.4 => 123
12.34 => 12
1.234 => 1.2
0.1234 => 0.12
0.01234 => 0.012
0.001234 => 0.0012
Is it any standard way to do it or should I reinvent the wheel myself?
Upvotes: 0
Views: 58
Reputation: 914
I couldn't figure out a way to do it, as it's a bit unconventional, but this extension may work:
public static string DoubleLimited(this double n){
return n < 100 ? $"{n:G2}" : n.ToString("#0.");
}
used like
var num = 1234.0;
Console.WriteLine(num.DoubleLimited());
Upvotes: 2