How to convert locale formatted number to BigInteger in Java?

心已入冬 提交于 2019-12-11 09:49:45

问题


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.



来源:https://stackoverflow.com/questions/12101470/how-to-convert-locale-formatted-number-to-biginteger-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!