Petr Mensik
Petr Mensik

Reputation: 27496

Displaying decimals in Java without trailing zeros

I came across this problem, I have a number of type long which represents time (only seconds and miliseconds). I would like to display it for example like this 1,124 ms. I thought that simple division would do the job, so I tried this code

 long time = 2;
 System.out.println(((float) time) / 1000);

But when the number has only one digit like in the example above, it's giving me 0,0020. So is there a way how to correct my formula or I have to manually cut the last zero?

Upvotes: 1

Views: 1492

Answers (2)

Jon Taylor
Jon Taylor

Reputation: 7905

Just use a formatting statement that makes it 3 decimal places

String.format("%.3f", floatValue);

If you need to find out more about number formatting check out this link

Upvotes: 5

sunil
sunil

Reputation: 6604

this will do the task

    long time = 2;
    float num = ((float) time) / 1000;
    DecimalFormat df = new DecimalFormat("#.###");
    String str = df.format(num);
    System.out.println(str);

Upvotes: 0

Related Questions