Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Formatting Currency in Java
Edwin Torres
Edwin Torres

Posted on • Edited on

     

Formatting Currency in Java

An easy way to output currency in Java is to use the built-inNumberFormat class. This lets you format a number like1000.2399 for output as$1,000.24.

NumberFormat rounds to two decimals, adds necessary commas, and includes a$ in front.

To use NumberFormat, import the class at the top of your program:

importjava.text.NumberFormat;
Enter fullscreen modeExit fullscreen mode

Next, create the NumberFormat object and assign it to a variableformatter:

NumberFormatformatter=NumberFormat.getCurrencyInstance();
Enter fullscreen modeExit fullscreen mode

Finally, use theformatter object to invoke theformat() method on the amount to be formatted:

doubleamt=1000.2399;StringamtFormatted=formatter.format(amt);
Enter fullscreen modeExit fullscreen mode

Note that the result is aString value.

Here is a full program example:

importjava.text.NumberFormat;publicclassNumberFormatExample{publicstaticvoidmain(String[]args){NumberFormatformatter=NumberFormat.getCurrencyInstance();doubleamt=1000.2399;StringamtFormatted=formatter.format(amt);System.out.println("original:    "+amt);System.out.println("formatted:   "+amtFormatted);}}
Enter fullscreen modeExit fullscreen mode

Here is the output:

original:    1000.2399formatted:   $1,000.24
Enter fullscreen modeExit fullscreen mode

Follow me on Twitter@realEdwinTorres for more programming tips and help.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Department Chief Engineer @MITREcorp. CS professor @monmouthu. Proud husband and father ❤️. My tweets are my own.
  • Location
    NJ
  • Education
    Doctor of Engineering, George Washington University
  • Work
    Principal Software Engineer at MITRE
  • Joined

More fromEdwin Torres

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp