【问题标题】:single decimal precision in javajava中的单十进制精度
【发布时间】:2015-11-26 19:48:23
【问题描述】:

我有一个双重身份,例如32.559

如何去掉除一位十进制数字之外的所有数字,使我的输出看起来像 32.5

【问题讨论】:

  • 参见 java.lang.Math.round 和 java.text.DecimalFormat
  • 缺乏自己的研究可能会导致很多反对意见......您应该添加您尝试过的内容以及为什么它不符合您的要求。
  • 请下次至少做一些研究工作。使用您的 exact 标题副本并粘贴的 google 搜索显示了这个明显的重复项:How to round a number to n decimal places in Java

标签: java function format


【解决方案1】:

你可以使用DecimalFormat

Locale locale  = new Locale("en", "UK");
String pattern = "###.#";

DecimalFormat decimalFormat = (DecimalFormat)
NumberFormat.getNumberInstance(locale);
decimalFormat.applyPattern(pattern);

String format = decimalFormat.format(32.559);
System.out.println(format);

此代码打印的输出将是:

32.5

这是上面的基本内容,你可以去 throws here 了解更多详情。

【讨论】:

  • 它不会把它四舍五入打印32.6吗?
  • 这对我来说输出 32.6
【解决方案2】:

我假设你只是想这样打印:

String result = String.format("%.1f", value);

【讨论】:

    【解决方案3】:
    float f = 32.559f;
    System.out.printf("%.1f", f);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多