Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format long numbers?

If I have a number that is 100,000,000 how can I represent that as "100M" in a string?

like image 505
Sheehan Alam Avatar asked Feb 04 '23 02:02

Sheehan Alam


1 Answers

To my knowledge there's no library support for abbreviating numbers, but you can easily do it yourself:

NumberFormat formatter = NumberFormat.getInstance();
String result = null;
if (num % 1000000 == 0 && num != 0) {
   result = formatter.format(num / 1000000) + "M";
} else if (num % 1000 == 0 && num != 0) {
   result = formatter.format(num / 1000) + "K";
} else {
   result = formatter.format(num);
}

Of course, this assumes that you don't want to shorten a number like 1,234,567.89. If you do, then this question is a duplicate.

like image 65
Aaron Novstrup Avatar answered Feb 05 '23 14:02

Aaron Novstrup