在C#中设置小数的精度 [英] Set the precision for Decimal numbers in C#

查看:772
本文介绍了在C#中设置小数的精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以全局更改C#中小数的精度?

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

在TypeScript中,我使用的框架是 Decimal.js ,在这里我可以像这样 Decimal.set({precision:15 })。这意味着该操作最多返回15个十进制数字。

In TypeScript I am using the framework Decimal.js, where I can change the precision of the Decimal operations globally like so Decimal.set({ precision: 15}). This means that the operation will return at most 15 decimal digits.


  • TypeScript :操作 5/3 返回 1.66666666666667

  • C#操作 5m / 3m 返回 1.6666666666666666666666666666667

  • TypeScript:the operation 5/3 returns 1.66666666666667
  • C# the operation5m/3m returns 1.6666666666666666666666666667

C#中的小数值是否有类似的设置?我该如何在C#中完成此操作?

Is there some similar setting for Decimal values in C# ? How can I accomplish this in C# ?

推荐答案

这并非您要的完全,但是您可以初始化<全局范围内的code> NumberFormatInfo 对象,并使用它来格式化小数。下面是一个示例:

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链接: https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo (v = vs.110).aspx

NumberDecimalDigits用法示例: https://msdn.microsoft.com/zh-cn/library/system.globalization.numberformatinfo.numberdecimaldigits( v = vs.110).aspx

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

这篇关于在C#中设置小数的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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