简体   繁体   English

Java中的截断或DecimalFormat

[英]Truncation or DecimalFormat in Java

I have this: 我有这个:

if (inKm) 
{
    text = String.valueOf(MetricConverter.milesToKilometers(Double.valueOf(text)));

}

This yields a result into a JTextField that is a bit too long for my liking. 这产生了一个JTextField的结果,对于我来说有点太长了。 How do I truncate or use decimalformat on the resulting value? 如何截断或对结果值使用小数格式? When I used decimalformat within this expression it just bugged out the program. 当我在此表达式中使用小数格式时,它只是将程序弄错了。

I like to use this since it's so similar to printf() 我喜欢使用它,因为它与printf()非常相似

double doubleValue = 123.4567895;
String.format("%.2f", doubleValue); // returns "123.46"

Edit: This does not truncate, but rounds half-up. 编辑:这不会截断,但会四舍五入。

More info on how to use the String.format() , and java.util.Formatter : 有关如何使用String.format()java.util.Formatter更多信息:
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM