Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java localizing number formatting

Java uses period in decimals, e.g. 1/2 = 0.5

Is there any way to make it use comma instead, as in 1/2 = 0,5? And not to use comma for thousands (as in one hundred thousand = 100,000) but use space instead (100 000)?

When it comes to output I suppose I could use all sorts of string format functions, but the problem is input (JTable). Some columns require Double format so users must enter something like 45.5 and in these parts they are used to 45,5 :) Thanks in advance

Update:

I tried using myTable.setDefaultLocale(Locale.Germany); but it didnt work. I also did Locale.setDefault(Locale.Germany); @ main function and it did work but in rather silly way: while cell is in editing mode, you must enter dot as normal, i.e. 45.5 but after you hit enter to confirm changes, it is displayed as comma: 45,5. I mean it uses comma only for display purposes, but when editing its still same ol' dot.

Is there any way to fix it without writing custom table model?

like image 436
Sejanus Avatar asked Feb 28 '23 19:02

Sejanus


2 Answers

Take a look at Formatting and Parsing a Number for a Locale:

// Format for CANADA locale
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1,234.56

// Format for GERMAN locale
locale = Locale.GERMAN;
string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1.234,56

// Format for the default locale
string = NumberFormat.getNumberInstance().format(-1234.56);


// Parse a GERMAN number
try {
    Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
    if (number instanceof Long) {
        // Long value
    } else {
        // Double value
    }
} catch (ParseException e) {
}
like image 81
cletus Avatar answered Mar 11 '23 03:03

cletus


Thus, you basically want to convert a localized String representation supposedly in a numerical format into a Number/BigDecimal and vice versa?

There you have the java.text.DecimalFormat for. To learn more, consult Sun's own tutorial about the subject.

To localize your Swing application, use JComponent#setDefaultLocale(). E.g.

JComponent.setDefaultLocale(Locale.GERMANY);
like image 23
BalusC Avatar answered Mar 11 '23 01:03

BalusC