【问题标题】:How to set String to float [duplicate]如何将字符串设置为浮动[重复]
【发布时间】:2018-06-04 06:30:32
【问题描述】:

我正在尝试获取一个字符串,将其强制为浮点数,然后将其格式化为“###.##”(我可以做到),最后将其发送到浮点变量(这是我遇到问题的地方)。

当我在该变量上使用 Float.parseFloat() 时,我的浮点数的格式为“###.#”,我需要浮点数的格式完全为“###.##”,即使原始字符串也是如此是“321”。

    String priceLabel = "321";
    float priceLabelConvertedInFloat = Float.parseFloat(priceLabel);
    System.out.println(priceLabelConvertedInFloat);

    NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    DecimalFormat df = (DecimalFormat)nf;
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);

    String priceStringWith2Decimals = df.format(priceLabelConvertedInFloat);
    System.out.println(priceStringWith2Decimals);

    float finalPrice = Float.parseFloat(priceStringWith2Decimals);
    System.out.println(finalPrice);

它打印 “321.0” -> 预期 / “321.00” -> 预期 / “321.0” -> 不想要 :(

感谢您提供的任何帮助。

【问题讨论】:

  • 浮点数没有十进制数字,并且它不跟踪小数部分的尾随零,即使对于二进制小数也是如此。您应该始终使用 NumberFormat 或 String.format 来输出浮点数

标签: java string parsing type-conversion


【解决方案1】:

您可以将最终打印语句更改为:

System.out.printf("%.2f", finalPrice);

【讨论】:

  • 你可能想添加一个换行符,让它像 System.out.println:"%.2f%n"
猜你喜欢
  • 2013-05-30
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-20
  • 2015-02-15
  • 2018-12-28
  • 2019-11-21
相关资源
最近更新 更多