使用Java中的数字格式化器

huangapple go评论55阅读模式
英文:

Using Number formater java

问题

我正在尝试使用Java中的数字格式化器(Number Formatter)将整数格式化为紧凑的数字格式,例如将1000格式化为1k,但是出现了错误。

我的代码如下:

package com.project.newproject;
import java.text.NumberFormat;
import java.util.Locale;

protected void onCreate(Bundle _savedInstanceState) {
    super.onCreate(_savedInstanceState);
    setContentView(R.layout.main);
    NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
}

如何修复错误:
Style 无法解析或不是一个字段。

如何解决 "Style cannot be resolved" 的问题。

英文:

I am try to use number formatter in java to formart intiger in to compact number fomart like 1000 to 1k but it give error
My code

package com.project.newproject;
import java.text.NumberFormat;
import java.util.Locale;

protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.main);
NumberFormat formatter =  NumberFormat.getCompactNumberInstance( Locale.US,NumberFormat.Style.SHORT);

	}

How to fix the error:
Style cannot be resolved or is not a field

How to fix issue Style cannot be resolved.

答案1

得分: 1

请看这里,尝试使用这段代码,它将解决你的问题。

public static String formatValue(float value) {
  String arr[] = {"", "K", "M", "B", "T", "P", "E"};
  int index = 0;
  while ((value / 1000) >= 1) {
      value = value / 1000;
      index++;
  }
  DecimalFormat decimalFormat = new DecimalFormat("#.##");
  return String.format("%s %s", decimalFormat.format(value), arr[index]);
}

这段代码可以将一个浮点数值格式化为带有单位的字符串。它使用了一个字符串数组 arr 来存储单位(例如K、M、B等),然后根据值的大小选择合适的单位。最后,使用 DecimalFormat 类来格式化值,并使用 String.format 方法将值和单位拼接成最终的字符串返回。

英文:

Here you go, try using this, it will solve your problem

    public static String formatValue(float value) {
      String arr[] = {"", "K", "M", "B", "T", "P", "E"};
      int index = 0;
      while ((value / 1000) >= 1) {
          value = value / 1000;
          index++;
      }
      DecimalFormat decimalFormat = new DecimalFormat("#.##");
      return String.format("%s %s", decimalFormat.format(value), arr[index]);
    }

huangapple
  • 本文由 发表于 2023年1月8日 22:01:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定