You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add comma between them. Mostly numbers which are used to represent monetary value e.g. price, amount etc requires comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollar then you would like to see it as 1,000,000 rather than 1000000. Clearly first one is more readable the second one. Of course you can further format to add currency based upon locale, but this tutorial is not about that. In this tutorial, we are just looking to format numbers and group them. Its second part of my number formatting article, in first part you have learned how to format floating point numbers in Java and in this article shows step by step example to group numbers and add commas between them. There are mainly two ways to group numbers in Java, first by using NumberFormat class and second by using DecimalFormat class. Actually DecimalFormat is sub class of NumbeFormat and method used to enable grouping e.g. setGroupingUsed() is define there, but you cannot specify grouping size there. Grouping size is the number of digits between grouping separators in the integer portion of a number and by default NumberFormat use group size of three. So if grouping is your need and you are happy with grouping size of three then go for NumberFormat but if you want advanced formatting and custom grouping size then go for DecimalFormat class. If you are beginner in Java and interested in learning essential features e.g. text formatting, I suggest to take a look at Java: A Beginner's Guide by Herbert Schildt, a must read book for Java beginners.
Read more »
No comments:
Post a Comment