-1

I am currently working on salary disbursement module in Spring MVC, in application level, i store my salary data in double type, eg double amount=32690597

i want to format it like 32,690,597, so it become more readable.

Suggest me the best solution for this thank you

Filburt
  • 17,626
  • 12
  • 64
  • 115
user9634982
  • 565
  • 5
  • 24

3 Answers3

3
System.out.println(String.format("%1$,.0f", amount));

OR

String formatAmount = new DecimalFormat("#,###,###,###,###").format(amount);

OR - Java 8

NumberFormat numberFormatter = NumberFormat.getNumberInstance(Locale.ENGLISH);
String formatAmount = numberFormatter.format(amount);
Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
2

Use DecimalFormat for this problem.

double amount = 32690597;
//create pattern for decimal format
String pattern = "###,###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);

//change dot with comma
String formattedNumber = decimalFormat.format(amount).replace(".",",");

In detail Decimal Formatter keys ;

0   A digit - always displayed, even if number has less digits (then 0 is displayed)
#   A digit, leading zeroes are omitted.
.   Marks decimal separator
,   Marks grouping separator (e.g. thousand separator)
E   Marks separation of mantissa and exponent for exponential formats.
;   Separates formats
-   Marks the negative number prefix
%   Multiplies by 100 and shows number as percentage
?   Multiplies by 1000 and shows number as per mille
¤   Currency sign - replaced by the currency sign for the Locale. Also makes formatting use the monetary decimal separator instead of normal decimal separator. ¤¤ makes formatting use international monetary symbols.
X   Marks a character to be used in number prefix or suffix
'   Marks a quote around special characters in prefix or suffix of formatted number.

Some Examples with this ;

Pattern      Number        Formatted String
###.###      123.456       123.456
###.#        123.456       123.5
###,###.##   123456.789    123,456.79
000.###      9.95          009.95
##0.###      0.95          0.95
drowny
  • 2,067
  • 11
  • 19
1
static String formatDouble(double input){
    String inputString = new String(Double.toString(input));
    char[] array= inputString.toCharArray();
    StringBuilder str = new StringBuilder("");
    for(int i = array.length-1; i >= 0; i--){
        str.insert(0, array[i]);
            if(i % 3 == 0 && i != 0){
            str.insert(0, ",");
            }
        }
    return str.toString();
    }

Hope this helps

Better use String.format

  • Thanks so much dear,it seems the traditional and manual way to achieve the same, it literally improves the learning capability of a beginner and yeah congrats to you to be part of code of conduct.All the best – user9634982 Sep 13 '18 at 09:44
  • Thank you, I updated the code as it was relying on certain aspects of the compiler. The updated example above should work every where. – theMahaloRecords Sep 13 '18 at 11:29