如果小数位是 .00,则需要忽略字符串中的小数位
need to ignore decimal places from string if decimal places is .00
大家好我想忽略这个.00
来自字符串编号。下面是我的样本输入和需要的输出。我试过这段代码。 String.Format ("{0: n}", Amount)
但是这段代码有问题。
如果值为 10000. 00
.
我的代码会将其转换为 "10, 000.00"
但我只需要 "10, 000"
。
请帮我解决这个问题。
更多例子:
10000.00 -> "10,000"
10000.12 -> "10,000.12"
10000.1 -> "10,000.10"
使用这种格式String.Format ("{0:0.##}", Amount)
或使用千位分隔符:"{0:#,0.##}"
by @Dmitry Bychenko
转换为整数将删除您的小数位,N2 格式将用作千位分隔符。
([int]10000.00).ToString("N");
您可以再添加一个扩展程序
var Amount = "1000.00";
var r = String.Format("{0: n}", Amount).Replace(".00", "");
所以你有某种钱:我们输出美分当且仅当我们有它们时:
10000.00 -> 10,000 (no cents; exactly 10000)
10000.003 -> 10,000 (no cents; still exactly 10000)
10000.1 -> 10,000.10 (ten cents)
10000.12 -> 10,000.12 (twelve cents)
10000.123 -> 10,000.12 (still twelve cents)
最后三种情况我们可以格式化为"#,0.00"
,前两种情况将是正确的"#,0"
格式字符串。唯一的问题是区分个案。
我们可以尝试为此使用 Math.Round()
string result = d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0");
演示:
decimal[] tests = new decimal[] {
10000.00m,
10000.003m,
10000.10m,
10000.12m,
10000.123m,
};
string report = string.Join(Environment.NewLine, tests
.Select(d =>
$"{d,-10} -> {d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0")}"));
Console.Write(report);
结果:
10000.00 -> 10,000
10000.003 -> 10,000
10000.10 -> 10,000.10
10000.12 -> 10,000.12
10000.123 -> 10,000.12
大家好我想忽略这个.00
来自字符串编号。下面是我的样本输入和需要的输出。我试过这段代码。 String.Format ("{0: n}", Amount)
但是这段代码有问题。
如果值为 10000. 00
.
我的代码会将其转换为 "10, 000.00"
但我只需要 "10, 000"
。
请帮我解决这个问题。
更多例子:
10000.00 -> "10,000"
10000.12 -> "10,000.12"
10000.1 -> "10,000.10"
使用这种格式String.Format ("{0:0.##}", Amount)
或使用千位分隔符:"{0:#,0.##}"
by @Dmitry Bychenko
转换为整数将删除您的小数位,N2 格式将用作千位分隔符。
([int]10000.00).ToString("N");
您可以再添加一个扩展程序
var Amount = "1000.00";
var r = String.Format("{0: n}", Amount).Replace(".00", "");
所以你有某种钱:我们输出美分当且仅当我们有它们时:
10000.00 -> 10,000 (no cents; exactly 10000)
10000.003 -> 10,000 (no cents; still exactly 10000)
10000.1 -> 10,000.10 (ten cents)
10000.12 -> 10,000.12 (twelve cents)
10000.123 -> 10,000.12 (still twelve cents)
最后三种情况我们可以格式化为"#,0.00"
,前两种情况将是正确的"#,0"
格式字符串。唯一的问题是区分个案。
我们可以尝试为此使用 Math.Round()
string result = d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0");
演示:
decimal[] tests = new decimal[] {
10000.00m,
10000.003m,
10000.10m,
10000.12m,
10000.123m,
};
string report = string.Join(Environment.NewLine, tests
.Select(d =>
$"{d,-10} -> {d.ToString(Math.Round(d) != Math.Round(d, 2) ? "#,0.00" : "#,0")}"));
Console.Write(report);
结果:
10000.00 -> 10,000
10000.003 -> 10,000
10000.10 -> 10,000.10
10000.12 -> 10,000.12
10000.123 -> 10,000.12