2

Thousand separator: "." (dot) Decimal separator: "," (comma). I live in Italy.

I'm getting from API this value (it's a string):

"balance":"1254.00".

In a case I need to convert it in an integer value:

1.254

without the decimal part (also if it is not zero, without round up or down).

In another case I could have (it's a string):

"balance":"1234.56"

And in that case I need

1.234,56

Going crazy with several functions, not getting my goal.

E.g. I tried:

NumberFormat numberFormat = new DecimalFormat("#,##");
BigDecimal balance_numeric = new BigDecimal(this.raw_balance.replaceAll(",", ""));
balance = String.valueOf(numberFormat.format(balance_numeric));

And getting for first case (1254) an 12,54 , no sense for me.

Thank you very much.

sineverba
  • 5,059
  • 7
  • 39
  • 84

2 Answers2

0

The code is pretty much self-explanatory. Do comment if you need help. :)

DecimalFormat format = new DecimalFormat();
DecimalFormatSymbols sm = DecimalFormatSymbols.getInstance();
sm.setDecimalSeparator(',');
sm.setGroupingSeparator('.');
format.setDecimalFormatSymbols(sm);
System.out.println(format.format(1254.02));

EDIT 1

There is an alternative which I didn't know about.

NumberFormat nf = NumberFormat.getNumberInstance(Locale.ITALIAN);
DecimalFormat df = (DecimalFormat)nf;

You can use the Locale to do awesome stuff!

denvercoder9
  • 2,979
  • 3
  • 28
  • 41
0

If I understand right, the API always returns a decimal number. If the decimal part is zero you want the integer part of the number. If not, you wants the whole decimal number.

    String s = "1234.00";
    Double d = new Double(s);

    double f = d - d.longValue();
    if (f == .0) {
        // format d.longValue() as int
    } else {
        // format d as double
    } 
PeterMmm
  • 24,152
  • 13
  • 73
  • 111