[英]What is the c# equivalent of Java DecimalFormat?
How would I convert the following code to C# 我如何将以下代码转换为C#
DecimalFormat form
String pattern = "";
for (int i = 0; i < nPlaces - nDec - 2; i++) {
pattern += "#";
}
pattern += "0.";
for (int i = nPlaces - nDec; i < nPlaces; i++) {
pattern += "0";
}
form = (DecimalFormat) NumberFormat.getInstance();
DecimalFormatSymbols symbols = form.getDecimalFormatSymbols();
symbols.setDecimalSeparator('.');
form.setDecimalFormatSymbols(symbols);
form.setMaximumIntegerDigits(nPlaces - nDec - 1);
form.applyPattern(pattern);
EDIT The particular problem is that I do not wish the decimal separator to change with Locale (eg some Locales would use ','). 编辑特别的问题是我不希望小数分隔符改变Locale(例如,一些Locales会使用',')。
For decimal separator you can set it in a NumberFormatInfo
instance and use it with ToString: 对于小数分隔符,您可以在
NumberFormatInfo
实例中设置它并将其与ToString一起使用:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
//** test **
NumberFormatInfo nfi = new NumberFormatInfo();
decimal d = 125501.0235648m;
nfi.NumberDecimalSeparator = "?";
s = d.ToString(nfi); //--> 125501?0235648
to have the result of your java version, use the ToString()
function version with Custom Numeric Format Strings (ie: what you called pattern): 要获得java版本的结果,请使用带有自定义数字格式字符串的
ToString()
函数版本(即:您所谓的模式):
s = d.ToString("# ### ##0.0000", nfi);// 1245124587.23 --> 1245 124 587?2300
// 24587.235215 --> 24 587?2352
System.Globalization.NumberFormatInfo System.Globalization.NumberFormatInfo
In C#, decimal numbers are stored in the decimal
type, with an internal representation that allows you to perform decimal math without rounding errors. 在C#中, 十进制数以
decimal
类型存储,内部表示允许您执行十进制数学运算而不会出现舍入错误。
Once you have the number, you can format it using Decimal.ToString() for output purposes. 获得数字后,可以使用Decimal.ToString() 格式化它以进行输出。 This formatting is locale-specific;
此格式是特定于语言环境的; it respects your current culture setting .
它尊重您当前的文化背景 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.