0

I have a few doubles in my code that need to output with no more than two decimal places while ignoring trailing zeros. For example:

    2.0334=2.03  
    10.20=10.2  
    24.0032=24

I also have other doubles that I have to output with different formats, including trailing zeros and different precisions. Multiple formats may be output in the same System.out.format() line. From what I know about DecimalFormat (which, admittedly, isn't much), I can't output two decimals with different formats on the same line. I'm trying to use System.out.format() for that reason, but I can't make it ignore trailing zeros. Is this possible, or am I stuck with only DecimalFormat? Thanks!

1
  • 1
    You can output two numbers with different formats on the same line using multiple instances of DecimalFormat. If that's what you want to do. You just can't use the same instance to format in two different ways at the same time. Commented Feb 12, 2014 at 0:32

1 Answer 1

1

You can use different instances of DecimalFormat to format various numbers as you wish first and print them afterwards.

double num1 = 2.0334;  
double num2 = 10.2;
double num3 = 24.0032;

DecimalFormat df1 = new DecimalFormat("#.##");
DecimalFormat df2 = new DecimalFormat("#.#");
DecimalFormat df3 = new DecimalFormat("#");

System.out.print(String.format("%s %s %s", df1.format(num1), df2.format(num2),
        df3.format(num3));

Or straight away using formatted output of printf(),

System.out.printf("%.2f %.1f, %.0f", num1, num2, num3);
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for this, wasn't aware I could do that. But for my own curiosity, is there any way to do it without DecimalFormat? For example (with made up syntax): System.out.format("%.2f, %.3f", double1(ignoreZeros), double2) ?
Yup you can, and you almost nailed the syntax too, check System.out.prinf() documentation for details.
I'm looking through the documentation, but I don't see any way to remove trailing zeros from a double. Leading zeros, yes, but not trailing zeros. Any way you'd be willing to show me the syntax you're talking about? Thanks!
If you want to remove trailing zeroes, I'd say you have to stick to DecimalFormat(), or do it manually, no way of doing it through formatted string output I know of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.