Java: What is the correct way to convert String to a real amount of money (BigDecimal)

I need to convert an incoming string field to a BigDecimal field that will represent the actual amount of money, for example:

String amount = "1000";

BigDecimal valid_amount = convert(amount);

print(valid_amount.toString())//1000.00

What is the correct API to use converting strings to real money in Java (ex: apache commons library)?

Thanks in advance,

+3
source share
5 answers

How about a constructor BigDecimal(String)?

String amount = "1000";
BigDecimal validAmount = new BigDecimal(amount);
System.out.println(validAmount); // prints: 1000

If you want to format the output in different ways, use the class Formatter.

+8
source

You wanted to achieve the following :?

NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(new BigDecimal("1000")));

Output

$1,000.00
+4
source

new BigDecimal(strValue).

, The Evil BigDecimal Constructor

0
source

There is a Joda-Money library for working with monetary values. But, according to the website, "the current development release is for feedback, not for use in production."

0
source

If you want to print a decimal value using the setScale method

String amount = "1000";
BigDecimal validAmount = new 
BigDecimal(amount).setScale(2,RoundingMode.CEILING);
System.out.println(validAmount); // prints: 1000.00
0
source

Source: https://habr.com/ru/post/1740385/


All Articles