In this post we will talk and learn How to design Money Class in Java ?
Money is basically composed of two fundamental entities Amount and Currency.
The BigDecimal is ideal data type provided in Java language for representing monetary values and Java also provides
Currency Class implementation.
Money class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.kkjavatutorials.monetary; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Currency; import java.util.Locale; /** * @author KK JavaTutorials * This class shows how to design Money Class in Java */ public class Money{ private static final Currency CURRENCY = Currency.getInstance(new Locale("en","us")); private static final NumberFormat NUMBERFORMAT = NumberFormat.getCurrencyInstance(new Locale("en", "us")); private final BigDecimal amount; private final Currency currency; public static Money monetaryAmount(BigDecimal amount) { return new Money(amount, CURRENCY); } public Money(BigDecimal amount, Currency currency) { this.amount = amount; this.currency = currency; } public BigDecimal getAmount() { return amount; } public Currency getCurrency() { return currency; } @Override public String toString() { return NUMBERFORMAT.format(amount); } } |
Note:
The code shown above is not thread safe, ideally NumberFormat should be created local to a thread using ThreadLocal class instead making it a static field of class.
Client program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kkjavatutorials.client; import java.math.BigDecimal; import com.kkjavatutorials.monetary.Money; public class ClientTest { /** * @param KK JavaTutorials * Now let's use Money class to represent monetary amount */ public static void main(String[] args) { Money money = Money.monetaryAmount(new BigDecimal("900")); System.out.println("Amount = " + money); } } |
Sample output of above program:
Amount = $900.00
That’s all about How to design Money Class in Java?
You May Also Like:
Which data type would you choose for storing currency values like Trading Price in Java?
How would you print a given currency value for Indian Locale (INR Currency)?
Which classes in java are immutable ?
How would you round a double value to certain decimal Precision and Scale ?
What is BlockingQueue? How can we implement Producer and Consumer problem using Blocking Queue?
How to get number of available processors in Java ?
If you have any feedback or suggestion please feel free to drop in blow comment box.