What is the C # Java DecimalFormat equivalent?

How to convert the following code in 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 specific problem is that I do not want the decimal separator to be changed using Locale (for example, some Locales would use ",").

+6
java c # decimalformat
source share
2 answers

For the decimal separator, you can set it in an instance of NumberFormatInfo 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 get the result of your java version, use the version of the ToString() function with custom strings of a number format (i.e.: what you called a pattern):

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

System.Globalization.NumberFormatInfo

+8
source share

In C #, decimal numbers are stored in decimal type with an internal representation that allows you to perform decimal math without rounding off the error.

Once you have a number, you can format it using Decimal.ToString () for output. This formatting is locale specific; he respects your current culture setting .

+3
source share

All Articles