Monday, December 04, 2006

How to force decimal separator char upon java region code?

Java application could be run on any compliant platform. And that's great. But, when you provide it to your customer, you don't know the region code of his server. For exemple, you don't know if is configured to work in english or french.

By the way, let's take the previous example. In franch, decimal separator char is ',' (comma). In english, it is '.' (dot). When prensenting data to end user, you probably want to ensure that the decimal separator char is the right. So, you can for it usiing DecimalFormat.

Let's see it in the following code :

public class AfficheurDecimal {

public AfficheurDecimal() {
testerReste(100);
testerReste(0);
testerReste(12354.12854);
}

private void testerReste(double reste) {
if (reste != 0) {
DecimalFormat formatEntier = new DecimalFormat("0.00");
DecimalFormatSymbols symbols = formatEntier.getDecimalFormatSymbols();
symbols.setDecimalSeparator(',');
formatEntier.setDecimalFormatSymbols(symbols);
String msg = "Il reste " + formatEntier.format(reste) + " à ventiler";
System.out.println(msg);
}
if (reste == 0) {
System.out.println("Pas de reste");
}
}


/**
* Auteur : a.depellegrin

* Définition :

* @param args
*/
public static void main(String[] args) {
new AfficheurDecimal();
}

}

That's all!

4 comments:

Anonymous said...

Very usefull.
Thanks a lot!

Romulo F.F. said...

First 4 lines from testerReste i prefered to make like this:

Locale brasil = new Locale( "pt", "BR" );
DecimalFormat formatEntier = new DecimalFormat( "0.00", new DecimalFormatSymbols( brasil ) );

----------------------------
Other utils and sometimes necessary methods are:
numberFormat.setParseBigDecimal( true );
numberFormat.setDecimalSeparatorAlwaysShown( true );
numberFormat.setMinimumFractionDigits( 4 );

Alexandre de Pellegrin said...

You're right Romulo. I really like your solution.

Rahul said...

Thanks for the great information in your blog Selenium Training in Chennai