1

当我将此对象作为 JSON 传回时,它看起来像这样:

0.000000000000000e+000

我在 C# 中的代码是:

// get adjustments for user
IEnumerable<Severity> existingSeverities = 
    from s in db.AdjusterPricingGrossLossSeverities
    where s.type == type
    && s.adjusterID == adj.id
    select new Severity
    {
        id = s.severity,
        adjustment = Math.Round((double)s.adjustment, 2, MidpointRounding.AwayFromZero).ToString(),
        isT_E = (bool)s.isTimeAndExpense
    };

我怎样才能让它四舍五入到小数点后两位(0.00)?

4

4 回答 4

3

Use;

dec.ToString("#.##");

See this answer for more information

If it's a nullable double in a Console app do;

    double ? d = 2.22222;
    Console.WriteLine(d.Value.ToString("#.##"));
于 2013-06-14T13:24:55.000 回答
1

我认为你混淆了两件事。“真实”数字不是您所看到的。实数以二进制格式在内部存储。您看到的十进制数字在这种内部格式中不存在。您看到的是将此值转换为十进制表示形式的字符串。

将任何内部二进制表示转换为人类可见的字符串称为格式化。该Round函数不格式化。看这个例子:

double x = 0.123456000000000e+000;
double y = Math.Round(x, 2, MidpointRounding.AwayFromZero);
// y ====> 0.120000000000000e+000;

舍入函数更改内部值。您需要的可能不是更改值,而是仅用两位数显示未更改的值:

string formattedValue = x.ToString("N2");

如果您使用货币进行交易,请使用decimal而不是double. decimal在内部使用二进制编码的十进制格式。像 1/10 这样的值不能在计算机中精确地表示为二进制数,就像 1/7 不能用十进制表示法(0.142857142857...)精确表示一样。但是 1/10 在存储为decimal.

于 2013-06-14T13:50:55.870 回答
0

原来,这是一个 LINQ to SQL 问题。我做了这个,它的工作...

// get adjustments for user
IEnumerable<Severity> existingSeverities = 
    from s in db.AdjusterPricingGrossLossSeverities
    where s.type == type
    && s.adjusterID == adj.id
    select new Severity
    {
        id = s.severity,
        adjustment = roundtest(s.adjustment.GetValueOrDefault()),
        isT_E = (bool)s.isTimeAndExpense
    };

// test method...
public string roundtest(double num)
{
    return num.ToString("#.##");
}
于 2013-06-14T13:44:17.830 回答
0

尝试这个:

// get adjustments for user
IEnumerable<Severity> existingSeverities = 
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
    id = s.severity,
    adjustment = s.adjustment.GetValueOrDefault().ToString("0.##"),
    isT_E = (bool)s.isTimeAndExpense
 };

-编辑-

我认为也许您需要让 Severity 类有一个属性,该属性采用双精度并将字符串保存到 Severity.adjustment,如下所示:

 Severity
 {
      //rest of class as normal

      public double SetAdjustment
           {
                set { adjustment = value.ToString("0.00"); } }
           }
 }

-编辑,第 2 部分-

// get adjustments for user
IEnumerable<Severity> existingSeverities = 
from s in db.AdjusterPricingGrossLossSeverities
where s.type == type
&& s.adjusterID == adj.id
select new Severity
{
    id = s.severity,
    SetAdjustment = s.adjustment.GetValueOrDefault(),
    isT_E = (bool)s.isTimeAndExpense
 };

您的其余代码不需要更改,它仍应正常使用 (Severity variable).adjustment。这只是为了绕过这样一个事实,即无法保证将 .Net 的标准数字格式字符串转换为 SQL 的Convert,更不用说任何自定义格式了。

于 2013-06-14T13:35:49.973 回答