Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting currency in Java

In my current project, I am storing a currency value as an int which represents the number of cents. However, when the user inputs this value in a text field, they will most likely expect to enter it as a decimal value. Also, I would like to prepend a dollar sign if the user doesn't enter it manually. How can I leverage a JFormattedTextField to do much of this work for me? Or is there other solutions using pre-existing Swing components so that I don't have to reinvent the wheel by coding this all by hand?

like image 255
Code-Apprentice Avatar asked May 22 '26 11:05

Code-Apprentice


1 Answers

The NumberFormat is also suited to format a currency (see NumberFormat#getCurrencyInstance). And since you need a Format for the JFormattedTextField I would start there.

You can configure the NumberFormat to allow decimal values, and convert it later on in your code to an int without problems

like image 123
Robin Avatar answered May 24 '26 01:05

Robin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!