views:

194

answers:

3

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?

+5  A: 

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) {
}
cletus
+2  A: 
BalusC
The problem with this solution is that my table column accepts Double values only, and Double Java-style means USA/Canadian number formatting. I could make it accept String instead of Double and then parse/validate it manually, but isn't there a simpler solution? Something like SetGlobalLocale(Locale.German); and suddenly Java knows that 12,20 is a valid Double value so I dont need to change anything in my table... something like that? :)
Sejanus
I see, you're using Swing. I updated my answer (and the tags of this question).
BalusC
Thanks a lot, I believe this is what I need! So far I got it working, of sorts, its far better than nothing but something is still not exactly right. I updated original question if you have some time to look at it
Sejanus
+1  A: 

To process the input correctly, you can implement your own TableModel and overwrite the setValueAt method.

Oleg Ryaboy