我想将一个 double 类型的数字除以一个 int。我只需要字符串格式的 2 个 deicmal 位置的结果。就堆栈效率而言,执行此操作的最佳方法是什么?
double d=321321321313131233213213213213;
int i=123;
ToString(d/i); //what do I get when I do this? A double? A float?
public String ToString(float? result) //what should I cast the result?
{
return @String.Format("{0:#,0.##;} divided double by int", result);
}
最佳答案
ToString(d/i); //what do I get when I do this? A double? A float?
你会得到双倍的。将 double 除以 int 将得到 double 值。
public String ToString(float? result) //what should I cast the result?
你会得到一个 double
作为值,所以你最好在这里使用 double
。您永远不会获得可空类型,并且绝对不会因此获得 float
,因此使用 float?
是完全不合适的。
What is the best way to do this in terms of stack efficiency?
这真的不值得担心,当然,除非您分析并发现这确实是一个问题。构建字符串的成本远高于除法运算,而且两者都不太可能成为性能方面的热点。
一个干净的处理方法就是使用 double.ToString("N2") ,即:
double result = d/i;
string resultAsString = result.ToString("N2");
如果你想要一个完整的、格式化的字符串,你可以使用:
string resultAsString = string.Format("{0:N2} divided double by int", result);
关于c# - 有效地划分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11059700/