Li Cooper
Li Cooper

Reputation: 71

Truncating 0's from a double

I have a JTextField. I need to output there a double. Double is changing all the time (the program is a simple calculator). Possible options for the double are: 10.123, 22.1, 12.00023123, etc. The problem is that when I use String.format. it always gives me 5 decimal places after the "." Even if those are zeroes. Is there is a way to truncate those 0's when needed, but leave other numbers if any?

Thank you.

screen.setText(String.format("%10.5f", secondNumber));

Upvotes: 0

Views: 235

Answers (2)

Li Cooper
Li Cooper

Reputation: 71

I Used a combination of Jason's response and this:

String test = "" +Math.floor(secondNumber*1000)/1000;
screen.setText(String.format("%10s", test));  

That actually helped.Thanks.

Upvotes: 0

Jason Gordon
Jason Gordon

Reputation: 71

How about:

screen.setText(String.format("%10s", secondNumber));

It will display the minimum number of digits needed to preserve the value but no trailing zeros.

Upvotes: 1

Related Questions