【问题标题】:Set Text from String to Decimal Format将文本从字符串设置为十进制格式
【发布时间】:2016-11-25 03:57:13
【问题描述】:

我想让我的输出(TextView)从像 Rp.40000 这样的字符串变成 Rp.40.000

这是我的代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);
    //Mengambil data dari intent
    DecimalFormat formatter = new DecimalFormat("#,###,###");
    Intent i=getIntent();
    String npwp = i.getStringExtra(TAG_NPWP);
    String statusspp = i.getStringExtra(TAG_STATUSSPP);
    String tglsp2d= i.getStringExtra(TAG_TGLSP2D);
    String jumlahtotal = i.getStringExtra(TAG_JUMLAH);
    TextView textName=(TextView)findViewById(R.id.textName);
    TextView textLat=(TextView)findViewById(R.id.textLat);
    TextView textLon=(TextView)findViewById(R.id.textLon);
    TextView textPrice=(TextView)findViewById(R.id.textPrice);
    textName.setText("Nama : "+npwp);
    textLat.setText(statusspp);
    textLon.setText("TglSp2D : "+tglsp2d);
    textPrice.setText("Jumlah : Rp "+jumlahtotal);

【问题讨论】:

  • 你的问题是什么。没看懂?编辑您的问题。
  • @RizkiDeddySusanto,看来您从未使用过格式化程序。
  • textPrice.setText("Jumlah : Rp "+ formatter.format(jumlahtotal));
  • 你可以使用 NumberFormat.getInstance().format(longNumber)
  • 如果你有一个像 Rp.40000 这样的字符串并且想要添加一个小数,将字符串逐个字符地复制到一个空字符串中。然后,当您到达要添加小数的点时,添加它。然后打印新字符串

标签: java android string settext


【解决方案1】:

我希望这会有所帮助:

NumberFormat numberFormatter = NumberFormat.getCurrencyInstance(new Locale("in", "ID"));
textPrice.setText("Jumlah : "+ numberFormatter.format(40000));

而不是40000,传递你想要格式化的数字。

编辑:如果您拥有的值是一个字符串,并且它是一个有效数字:

NumberFormat numberFormatter = NumberFormat.getCurrencyInstance(new Locale("in", "ID"));
Double number = Double.parseDouble(yourString);
textPrice.setText("Jumlah : "+ numberFormatter.format(number));

【讨论】:

  • 值是来自 JSON 的字符串怎么样(jumlahtotal 是值)
  • @RizkiDeddySusanto,我已经编辑了答案,希望对您有所帮助。
  • 很高兴@RizkiDeddySusanto,请不要忘记验证这个答案。
【解决方案2】:

你可以使用

DecimalFormatSymbols.setGroupingSeperator

public static void main(String[] args) {
    int val = 40000;
    DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
    dfs.setGroupingSeparator('.');
    DecimalFormat formatter = new DecimalFormat("#,###",dfs);
    System.out.println(formatter.format(val));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2013-06-02
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多