two decimal places for decimal/money field

前端 未结 4 2132
半阙折子戏
半阙折子戏 2020-12-31 07:02

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

4条回答
  •  天涯浪人
    2020-12-31 07:37

    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).

    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).

    But I digress.

    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.

    To get fewer, you can

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

    Hope this helps.

    This program:

    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
    

    Cheers,

    N.

提交回复
热议问题