如何使用“。”来创建浮点数字符串(点)作为小数点分隔符,浮点后不超过3位数? [英] How to make strings from floating-point numbers with '.' (dot) as a decimal separator and not more than 3 digits after floating point?

查看:160
本文介绍了如何使用“。”来创建浮点数字符串(点)作为小数点分隔符,浮点后不超过3位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public String formatDouble(double d){
return String.format( ,d); //我应该在这里使用NumberFormat吗?





对于示例输入:

  1.00 
1,00
1,23
1.234567

我想得到这个输出:

  1 
1
1.23
1.234

如何配置模式(或者NumberFormat实例)生成正确的输出?

解决方案



  Decimalformat df = new DecimalFormat(0。###); 
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);

但是,小数点分隔符(点)将取决于当前的语言环境。要重写它,你可能想要提供自己的格式符号(参见 DecimalFormat.setDecimalFormatSymbols())。

I have this code:

public String formatDouble(double d) {
   return String.format("???", d); //Should I use NumberFormat here?
}

For the sample input:

1.00
1,00
1,23
1.234567

I would like to get this output:

1
1
1.23
1.234

How can I configure the pattern (or maybe NumberFormat instance) for producing the correct output?

解决方案

This would do roughly what you need:

Decimalformat df = new DecimalFormat("0.###");
df.setRoundingMode(RoundingMode.FLOOR);
df.format(1.2345);

However, the decimal separator (the dot) will be dependent on current locale. To override it, you may want to provide your own format symbols (see DecimalFormat.setDecimalFormatSymbols()).

这篇关于如何使用“。”来创建浮点数字符串(点)作为小数点分隔符,浮点后不超过3位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆