In this post, we will learn how to to format numbers in Java. Some times we need to format the number as per locale or as per our custom requirement. We also have a requirement to round the numbers. That’s when Formatting classes can help you. There are 2 important classes to format numbers in Java. NumberFormat DecimalFormat
 
package numbers;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

/**
 * Created by ssalunke on 14/04/2016.
 */
public class NumberFormatting {

    public static void main(String [] args) throws Exception{

        //Converting number to local geographical representation
        System.out.println("Number 564656 as in Germany -> "
                + NumberFormat.getNumberInstance(Locale.GERMANY).format(564656));

        System.out.println("Number 564656 as in France -> "
                + NumberFormat.getNumberInstance(Locale.FRANCE).format(564656));

        System.out.println("Number 564656 as in US -> " +
                NumberFormat.getNumberInstance(Locale.US).format(564656));


        //Adding $ to beginning of string
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale("En", "US"));
        String currencyString = numberFormat.format(120.99);
        System.out.println(currencyString);

        //Stripping $ from the string
        Number n = numberFormat.parse("$120");
        System.out.println("Number -> " + n.doubleValue());

        //Rounding the numbers
        double decimal = 6.3267;
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        System.out.println("After rounding the number to 2 decimal -> "+ Double.valueOf(decimalFormat.format(decimal)));

    }
}
Here is the output of above example.

Number 564656 as in Germany -> 564.656
Number 564656 as in France -> 564 656
Number 564656 as in US -> 564,656
$120.99
Number -> 120.0
After rounding the number to 2 decimal -> 6.33

Web development and Automation testing

solutions delivered!!