【问题标题】:How to convert locale formatted number to BigInteger in Java?如何在 Java 中将语言环境格式的数字转换为 BigInteger?
【发布时间】:2012-08-23 23:44:06
【问题描述】:

我搜索了很多,但没有任何帮助:(假设我需要将 12.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920(葡萄牙语组分隔符:.)转换为 BigInteger 值。如何进行转换?我尝试使用 NumberFormat、DecimalFormat 并没有任何效果,或者我的方法不对:(

【问题讨论】:

  • 你是怎么传入的?是字面意思,还是字符串?
  • 当我通过新的BigInteger( “12090129019201920192091029102901920192019201920”)工作得很好,但新的BigInteger( “12.090.129.019.201.920.192.091.029.102.901.920.192.019.201.920”)产生一个异常(如预期) .我传递了一个字符串,因为我正在实现一个字符串转换器来转换来自用户表单的输入。是否需要提供一个 Locale 实例来格式化我认为...但我不知道该怎么做

标签: java formatting numbers locale biginteger


【解决方案1】:

获取葡萄牙语LocaleNumberFormat 实例,然后获取带有它的号码的parse。这还将处理特定于语言环境的小数分隔符。

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

    删除分隔符不是更直接吗? Java 内部不关注这些。

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

    如果您需要它,那么您可以使用 NumberFormat.format() 来取回该值。

    【讨论】:

    • 一旦切换区域设置(例如从葡萄牙到美国),这将中断。 Joao 的语言环境 NumberFormat 要好得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2014-03-09
    • 1970-01-01
    • 2021-01-27
    相关资源
    最近更新 更多