c# - 有效地划分

标签 c# division

我想将一个 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/

相关文章:

c# - 在客户端上重置原始值时,DropDownList SelectedIndexChanged 不会运行

c# - 从数据库中完全替换 Entity Framework 数据模型似乎是不可能的

r - 除二向量

swift - 除完美因数时,除法需要更长的时间吗?

java - 如何检查变量是否为整数

c# - 如何在执行 Web 请求时指定仅连接超时?

c# - 通过代码C#在xml中的特定位置添加注释

c# - 使用 OpenTK/MonoTouch 从顶点列表中绘制?

java - 生成随机的简单数学除法问题

java - 数字除法