小数点后两位小数/钱场 [英] two decimal places for decimal/money field

查看:195
本文介绍了小数点后两位小数/钱场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有金钱字段的表在我的数据库。我已创建的实体,创造了钱场小数属性。当显示在我的MVC3认为字段的值,它有四个零0000这样的小数点后:5489.0000。我想说明只有两个00或小数。我怎样才能解决这个问题。为什么它显示小数点后四位连我声明的属性是十进制数。

I have a table with money field in my database. I have created entity and created decimal property for that money field. When the value of that field is displayed on My MVC3 view, It has four zeros 0000 after decimal like this : 5489.0000. I want to show only two 00 or decimal places. How can I fix it. Why it is showing four decimal places even I declared property as decimal.

请建议。

推荐答案

在SQL Server 数据类型在内部是一个64位整数的4位小数隐含规模。引用联机丛书,它是正确的,以十thousandsth一个货币单位的。它是一个小数点大致相当于(19,4)

The SQL Server money datatype internally is a 64-bit integer with an implied scale of 4 decimal places. To quote Books Online, it is accurate "to ten-thousandsth of a currency unit." It is, the rough equivalent of a decimal(19,4).

的原因的4而不是2的比例是维持precision在算术结果。你的普通币值为2的比例(例如:$ 3.27)乘法或缩放到小数点后2位两个数的除法得到一个结果是precise到小数点后4位:9.23 3.27分得到的2.82262996941896结果(约) 。你可以随身携带的结果无论精度的(小数位数),你的愿望。但是,结果仅 precise 的4位小数(2.8226)作为初始值只有precise为2位小数。这测量precise至(+/- 0.005)规定的最小单位的1/2以内。

The reason for the scale of 4 rather than 2 is to maintain precision in the results of arithmetic. Your ordinary currency value has a scale of 2 (e.g. $3.27) Multiplication or division of two numbers scaled to 2 decimal places gives a results that is precise to 4 decimal places: 9.23 divided by 3.27 yields a result of 2.82262996941896 (approximately). You can carry the result to whatever accuracy (number of decimal places) you desire. However, the result is only precise to 4 decimal places (2.8226) as the original values were only precise to 2 decimal places. That measurement is precise to within 1/2 of the smallest unit specified (+/- 0.005).

但是,我离题。

作为SQL Server 的结果具有4隐含的资金规模价值,ADO.Net价值为System.Decimal转换与4的规模和因为System.Decimal跟踪规模,当你将其转换为字符串,将小数点后4位。

As a result of a SQL Server money value having an implied scale of 4, ADO.Net converts the value to a System.Decimal with a scale of 4. And since System.Decimal tracks scale, when you convert it to string, you get 4 decimal places.

要获得较少的,可以


  • 圆形它转换之前,使用适当的 Decimal.Round()超载,或

  • 根据需要格式化(如(3.27M)的ToString(0.00);

  • Round it before conversion, using the appropriate Decimal.Round() overload, or
  • Format it as desired (eg. (3.27M).ToString("0.00") ;.

希望这有助于。

此程序:

namespace Sandbox
{
  using System ;
  class Program
  {
    static void Main( string[] args )
    {
      decimal pi     = (decimal) Math.PI ;
      string  piText = pi.ToString("0.00");
      Console.WriteLine("PI to 2 decimal places is {0} one way, and {1:0.00} another" , piText , pi ) ;
      return;
    }
  }
}

生成你所期望的:

Produces what you'd expect:

PI to 2 decimal places is 3.14 one way, and 3.14 another

干杯,

ñ。

这篇关于小数点后两位小数/钱场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆