0

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));
Li Cooper
  • 71
  • 1
  • 2
  • 12
  • Read String.format's documentation? – D. Ben Knoble Apr 20 '15 at 01:23
  • possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – Scary Wombat Apr 20 '15 at 01:25

2 Answers2

1

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.

  • It doesn't work. The problem with doubles is that they are not always precise. So, if I enter 1.333, the actual double may be 1.33300000111. So, I am getting the last number on the screen. Therefore, I need to truncate the number, I guess, and then print it out. – Li Cooper Apr 20 '15 at 15:58
  • String test = "" +Math.floor(secondNumber*1000)/1000; – Li Cooper Apr 20 '15 at 16:23
0

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.

Li Cooper
  • 71
  • 1
  • 2
  • 12