Java DecimalFormat 的 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);
编辑 特殊的问题是我不希望小数点分隔符随区域设置而更改(例如,某些区域设置会使用“,”)。
How would I convert the following code to 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 (e.g. some Locales would use ',').
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于小数点分隔符,您可以在
NumberFormatInfo
实例中设置它,并将其与 ToString 一起使用:要获得 java 版本的结果,请使用
ToString()
函数版本与 自定义数字格式字符串(即:您所说的模式):System.Globalization.NumberFormatInfo
For decimal separator you can set it in a
NumberFormatInfo
instance and use it with ToString:to have the result of your java version, use the
ToString()
function version with Custom Numeric Format Strings (i.e.: what you called pattern):System.Globalization.NumberFormatInfo
在 C# 中,十进制数存储在
decimal
类型,具有内部表示形式,允许您执行十进制数学运算而不会出现舍入错误。获得号码后,您可以格式化它使用 Decimal.ToString() 进行输出。这种格式是特定于语言环境的;它尊重您的当前的文化设置。
In C#, decimal numbers are stored in the
decimal
type, with an internal representation that allows you to perform decimal math without rounding errors.Once you have the number, you can format it using Decimal.ToString() for output purposes. This formatting is locale-specific; it respects your current culture setting.