【发布时间】:2015-10-04 08:17:12
【问题描述】:
我在 SQL 中有以下代码:
declare @test numeric(19,15) = 219.37345462345234235
SELECT str(@test,9,9) -- 219.37345
declare @test numeric(19,15) = 19.37345462345234235
SELECT str(@test,9,9) -- 19.373455
declare @test numeric(19,15) = 9.3
SELECT str(@test,9,9) -- 9.3734546
我怎样才能在 C# 中实现这一点,说我有
double d = 219.37345462345234235;
无论输入是什么,所需的输出都应包含 9 个字符,如以下示例中所示
下面的代码sn-p给出结果
public static string GetFormat(double quantity)
{
quantity = Math.Round(quantity,9-(Math.Truncate(quantity).ToString().Length));
string customQuantity = quantity.ToString().PadRight(9, '0');
if (customQuantity.Length > 9)
customQuantity = customQuantity.Substring(0, 9);
else if (customQuantity.Length == 9 && customQuantity.EndsWith("."))
customQuantity = customQuantity.Substring(0, 8);
return customQuantity;
}
这可以以更好的方式实现吗? 谢谢
【问题讨论】:
-
Math.Round(value, 5);呢? -
没有完全等价的。特别是,您必须自己处理“**”案例。
-
使用
string.format()或value.tostring()。