0

I'd like to use NumberFormat to convert a Double to a String. I'm currently using a NumberFormat based on a currency locale but this rounds the Double to 2 decimal places. How could I get it to not round the currency so that it includes fractional pennies?

So if I have

val doubleFormatMoney = 1.032323135

val format = NumberFormat.getCurrencyInstance(Locale.US)

val stringFormatMoney = format.format(doubleFormatMoney)

Then we should have stringFormatMoney = $1.032323135 but instead I get stringFormatMoney = $1.03

suleydaman
  • 463
  • 1
  • 7
  • 18
  • 4
    Why not include the applicable piece of code? It would make it easier to answer. – RealSkeptic Jun 25 '18 at 09:32
  • You change the NumberFormat chosen, https://docs.oracle.com/javase/10/docs/api/java/text/DecimalFormat.html – Peter Lawrey Jun 25 '18 at 09:34
  • What about System.out.println("" + new Double(1d/3d)); – Stefan Jun 25 '18 at 09:35
  • 2
    Note, one should not use Double to deal with money values in the first place, see http://www.javapractices.com/topic/TopicAction.do?Id=213 – cbley Jun 25 '18 at 09:37
  • US currency rounds to two decimal places, so your currency gets formatted that way. If you don't want your numbers to change and you only want to add a currency symbol to the front of your number, why don't you just make a method to do that? – James Whiteley Jun 25 '18 at 09:42

1 Answers1

2

The per-Locale currency format specification includes how many decimal places to use, since that varies by currency (some currencies use 3dp, for example the Jordanian Dinar). Therefore NumberFormat.getCurrencyInstance(Locale.US) includes rounding to 2dp by definition.

If you want to use the standard Double toString plus the Locale's currency symbol, you can do:

Currency.getInstance(Locale.US).getSymbol(Locale.US) + doubleFormatMoney

See How to get the currency symbol for particular country using locale?

Rich
  • 15,048
  • 2
  • 66
  • 119