【问题标题】:how to change the size of a number before the decimal point with DecimalFormat method如何使用 DecimalFormat 方法更改小数点前数字的大小
【发布时间】:2013-07-16 06:57:13
【问题描述】:

如何限制整数本身的位数而不仅仅是小数点后的小数部分?

例如使用数字 54321.12574857f 和 DecimalFormat("##0.##");它应该返回 543.12 或 321.12,小数点后两位是正确的,但是我想将小数点前的数字减少到只有 3。这是怎么做的?

在输入数字 54321.12574857 后,我使用 ##0.## 的 DecimalFormat 方法的参数,我期待 543.12,或者 321.12 而不是我得到的 54321.12

DecimalFormat 方法更改的唯一数字是小数点后的数字

            float inputNumber = 54321.12574857f;

    DecimalFormat decimalFormat = new DecimalFormat("##0.##");
    String newNumber = String.valueOf(decimalFormat.format(inputNumber));

    System.out.println(newNumber);

【问题讨论】:

  • 您不使用%的任何特殊原因?
  • 你能举出使用 % 的 String.format 的例子吗?当您提到 % 时,我假设您正在谈论 String.format 方法
  • 不.. 我的意思是使用mod 运算符。
  • 既然你说“我期待 543.12,或者 321.12”,你可以这样做decimalFormat.format(inputNumber % 1000)

标签: java android number-formatting decimalformat


【解决方案1】:

试试这样的,

    DecimalFormat decimalFormat = new DecimalFormat("##0.##");
    String newNumber = String.valueOf(decimalFormat.format(inputNumber/100));

【讨论】:

  • 这会起作用,唯一的问题是必须制定一种方法来将数字除以过大的位数。例如,现在它是 2 以上,所以你将除以 100 和 3 除以 1000,那么我需要一个 if else 的 switch 语句来继续检查有多少。
  • @Kevik 否则您可能无法通过这种方式删除前导数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 2016-10-30
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2012-02-17
相关资源
最近更新 更多