[英]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.我想格式化我的double
精度值,限制为 2 个重要位置,但不在 integer 部分数字中。
Currently I use G2
notation, but it displays number in scientific notation if integer part contains more than 2 places.目前我使用G2
表示法,但如果 integer 部分包含超过 2 个位置,它会以科学计数法显示数字。
Also I tried 0.##
, but it keeps 2 significant places in the fractional part no matter how many are there in the integer one.我也尝试了0.##
,但无论 integer 有多少,它都会在小数部分保留 2 个重要位置。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.