Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the c# equivalent of Java DecimalFormat?

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

like image 223
peter.murray.rust Avatar asked Oct 16 '09 08:10

peter.murray.rust


People also ask

What is C used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C language in simple words?

C is a structured, procedural programming language that has been widely used both for operating systems and applications and that has had a wide following in the academic community. Many versions of UNIX-based operating systems are written in C.

What is -= in C?

-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A.


2 Answers

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

like image 116
manji Avatar answered Sep 24 '22 00:09

manji


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.

like image 41
Robert Harvey Avatar answered Sep 26 '22 00:09

Robert Harvey