What is the c# equivalent of Java DecimalFormat?
Asked Answered
P

2

7

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 ',').

Pons answered 16/10, 2009 at 8:21 Comment(2)
It would be easier for us to help if you mention the higher level aim.Playsuit
Is there no simple equivalent? The actual aim is to make sure that FP numbers in different locales while retaing '.' as the decimal separatorPons
E
10

For decimal separator you can set it in a NumberFormatInfo instance and use it with 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 (i.e.: what you called pattern):

s = d.ToString("# ### ##0.0000", nfi);// 1245124587.23     --> 1245 124 587?2300
                                      //      24587.235215 -->       24 587?2352

System.Globalization.NumberFormatInfo

Electrolytic answered 16/10, 2009 at 8:30 Comment(0)
M
3

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.

Monumental answered 16/10, 2009 at 8:27 Comment(1)
To control the format, use Decimal.ToString(IFormatProvider)Warlord

© 2022 - 2024 — McMap. All rights reserved.