2

I searched a lot but nothing helped me :( Suppose I need convert 12.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920 (in Portuguese group separator: .) to BigInteger value. How to do that conversion? I tried use NumberFormat, DecimalFormat and nothing works or I didn't on right way :(

Lucas Batistussi
  • 2,183
  • 2
  • 25
  • 33
  • How did you pass it in? Was it literally that, or was it a String? – Makoto Aug 23 '12 at 23:47
  • When I pass new BigInteger("12090129019201920192091029102901920192019201920") works well, but new BigInteger("12.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920") generates an exception (as expected). I pass a string because I'm implementing a string converter to convert inputs from users forms. Is need provide an Locale instance to format I think... but I don't know how to do this – Lucas Batistussi Aug 23 '12 at 23:49

2 Answers2

9

Get a NumberFormat instance for a Portuguese Locale, and then parse the number with it. This will also handle locale-specific decimal separators.

NumberFormat nf = NumberFormat.getNumberInstance(new Locale("pt", "PT"));
DecimalFormat df = (DecimalFormat)nf;
df.setParseBigDecimal(true);
BigDecimal decimal = (BigDecimal)df.parse("12.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920");
BigInteger big = decimal.toBigInteger();

DEMO.

João Silva
  • 85,475
  • 27
  • 147
  • 152
1

Wouldn't it be more straightforward to remove the separators instead? Java doesn't pay attention to those internally.

String num = "2.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920";
BigInteger bigInt = new BigInteger(num.replaceAll("\\.", ""));

If you need it back, then you can use NumberFormat.format() to get the value back.

Makoto
  • 100,191
  • 27
  • 181
  • 221
  • This will break as soon as the locale is switched (say from Portugal to US). Joao's locale NumberFormat is much better. – Steve Kuo Aug 23 '12 at 23:53