简体   繁体   中英

C# Format double limiting significant digits but restrict scientific notation

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?

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM