Showing posts with label java - NumberFormat class. Show all posts
Showing posts with label java - NumberFormat class. Show all posts

Saturday, December 9, 2017

JAVA - How to format currency

double value = 35.4567;
    
/* get current currency formatter */
    
NumberFormat currency = NumberFormat.getCurrencyInstance();        

/* format to currency */
    
System.out.println( currency.format( value ) );
Output:
35,46 Kč
With java.text.NumberFormat you can change currency or for example set minimal number of decimal places.
double value = 35.4567;
    
/* get current currency formatter */
    
NumberFormat currency = NumberFormat.getCurrencyInstance();        
    
/* set to UK currency */
    
currency.setCurrency( Currency.getInstance( Locale.UK ) );
currency.setMinimumFractionDigits( 3 );
    
/* format to currency */
    
System.out.println( currency.format( value ) );
Output:
35,457 GBP

Tuesday, December 5, 2017

JAVAFX - How convent numeric to string with locale rules

This example convent double value to String with locale rules (first US, second French, third English):
@FXML TextArea memo;

private void btnActionOnAction(ActionEvent event) {
  double iValue = 1234567.2345;
  String sText;
    
  sText = "US = " + 
    NumberFormat.getNumberInstance( Locale.US ).format( iValue ) + "\n";
  sText += "French = " + 
    NumberFormat.getNumberInstance( Locale.FRENCH ).format( iValue ) + "\n";         
  sText += "English = " + 
    NumberFormat.getNumberInstance( Locale.ENGLISH ).format( iValue ) + "\n";         
    
  memo.setText( sText );    
}
How you can see, US adds thousand separator:
US = 1,234,567.235
French = 1 234 567,235
English = 1,234,567.235