How to convert locale formatted number to BigInteg

2019-08-14 12:09发布

问题:

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 :(

回答1:

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.



回答2:

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.