3

How can I display two decimal points after a number?

I have tried following:

var hrs = (from p in Hours.Where(h.UserName == UserName())
                              group p by p.Hours into g
                              select g.Sum(p => p.Hours)).Sum().ToString("#.##");

return Json(new { data = Convert.ToDouble(hrs).ToString("#.##") });

But it doesn't display anything on UI without Convert.ToDouble() and ToString("#.##") it displays hours "9"

How do we format results that we get by querying databases like above?

4

8 回答 8

2

Linq 查询的结果将是IEnumerabl<string>(或IQueryable<string>)。你需要做这样的事情:

var hrs = 
    (from p in Hours.Where(h.UserName == UserName())
     group p by p.Hours into g
     select g.Sum(p => p.Hours));

 return Json(new { data = hrs.Select(x => x.ToString("N2")) });
于 2013-07-22T17:48:37.397 回答
2

ToString("N2") 用于显示两位小数

var hrs = (from p in Hours.Where(h.UserName == UserName())
                          group p by p.Hours into g
                          select g.Sum(p => p.Hours)).ToString("#.##");
return Json(new { data = Convert.ToDouble(hrs).ToString("N2") });
于 2013-07-22T17:50:59.620 回答
1

您的查询结果不是单一的double,它是IEnumerable<double>您的用户所属的每个组的一个条目。

您需要.Sum()在结果中添加另一个(以获取您的用户所在的所有组的总和)。从那,你可以做到ToString("0.00")。你也不应该需要额外的Convert()ToString()

var hrs = (from p in Hours.Where(h => h.UserName == UserName())
   group p by p.Hours into g
   select g.Sum(p => p.Hours)).Sum().ToString("0.00");

return Json(new { data = hrs });

编辑:

改为。ToString("#.##")_ ToString("0.00")或者,使用ToString("N2").

编辑#2:

除非您的分组有某些原因,否则我会将您的 LINQ 语句和后续Json调用简化为:

var hrs = (from p in Hours
   where p.UserName == UserName()
   select p.Hours).Sum();

return Json(new { data = hrs.ToString("0.00") });
于 2013-07-22T17:52:42.547 回答
1

利用ToDouble(hrs).ToString("f2")

于 2013-07-22T17:46:51.057 回答
0

尝试:

Json(new { data = Convert.ToDouble(hrs).ToString("N2") });
于 2013-07-22T17:46:29.090 回答
0

尝试这个:

Json(new { data = String.Format("{0.00}",Convert.ToDouble(hrs))});
于 2013-07-22T17:48:24.143 回答
0

你也可以这样做:

return Json(new { data = Convert.ToDouble(hrs).ToString("#.00") });
于 2013-07-22T17:48:42.160 回答
0

感谢您的所有意见,他们肯定有助于提出以下解决方案:

Decimal.Parse(hrs.ToString()).ToString("N2")

有效的解决方案:

Convert.ToDecimal(hrs).ToString("N2")
于 2013-07-22T18:25:54.907 回答