Вопрос

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. 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()

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:
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top