Set the precision for Decimal numbers in C#

前端 未结 3 949
逝去的感伤
逝去的感伤 2020-12-17 15:57

Is it possible to change the precision for Decimal numbers in C# globally ?

In TypeScript I am using the framework Decimal.js, where I can change the precision of th

3条回答
  •  無奈伤痛
    2020-12-17 16:58

    This isn't exactly what you're asking, but you could initialize a NumberFormatInfo object within the global scope and use it to format decimals. Here is an example:

    NumberFormatInfo setPrecision = new NumberFormatInfo();
    
    setPrecision.NumberDecimalDigits = 2;
    
    decimal test = 1.22223;
    
    Console.Write(test.ToString("N", setPrecision)); //Should write 1.23
    
    setPrecision.NumberDecimalDigits = 3;
    
    test = 5m/3m;
    
    Console.Write(test.ToString("N", setPrecision)); //Should write 1.667
    

    MSDN Link: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo(v=vs.110).aspx

    NumberDecimalDigits usage example: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.numberdecimaldigits(v=vs.110).aspx

提交回复
热议问题