two decimal places for decimal/money field

前端 未结 4 2113
半阙折子戏
半阙折子戏 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:15

    Here is everything you need to know about formatting strings.

    http://blog.stevex.net/string-formatting-in-csharp/

    0 讨论(0)
  • 2020-12-31 07:17

    You have to format the string.

    One thing you can do if it money you want to display is:

    static void Main () 
    {
        decimal x = 0.999m;
        decimal y = 9999999999999999999999999999m;
        Console.WriteLine("My amount = {0:C}", x);
        Console.WriteLine("Your amount = {0:C}", y);
    }
    

    }

    OUTPUT: Output

    My amount = $1.00
    Your amount = $9,999,999,999,999,999,999,999,999,999.00

    the {0:C} is the currency Format

    Hope this helps!

    0 讨论(0)
  • 2020-12-31 07:23

    I used this and it worked:

    YourDecField.ToString("N")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题