Viewing 8 posts - 1 through 8 (of 8 total)
  • A little Java help please, printing float array values to 2 DP
  • mrjmt
    Free Member

    So, following on from previous post about beginners guides to making apps, I’ve decided to learn a little java.

    I’ve got my program working, only I’m stuck on one last part.

    I’ve got an array of float values called weights[]

    I can print these by saying:

    System.out.println("Weight 1:" +  weights[0]);
    System.out.println("Weight 2: " + weights[1]);
    System.out.println("Weight 3: " + weights[2]);
    System.out.println("Weight 4: " + weights[3]);

    Oh, I also know that I could do this with a loop, but it’ll change a little in future and the text descriptions will be different so I won’t be able to use a loop.

    I want to be able to print these but only to 2 decimal places.

    I thought I’d be able to use:
    System.out.println("Weight 1: %.2f", weights[0]);

    But it gives an error.

    I’m happy to round the values within the array to 2DP first, but I’m not sure how to do that either and would rather preserve the full value and just round it at the output.

    Any help would be great!

    flanagaj
    Free Member

    Just use the static Math.round(float) call.

    mrjmt
    Free Member

    Doesn’t that just round it to an int though? I need 2 decimal places.

    allthepies
    Free Member

    If I were in your shoes then I’d google “java round float”. The first hit has what you need.

    Edit: sorry didn’t read your question fully 🙂

    http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float-data-with-2-decimal-places-in-java

    Can’t paste in the answer but you need printf not println

    mrjmt
    Free Member

    Edit for your edit (!)

    As above, I’ve tried that but it doesn’t seem to like picking up the float from an array?

    allthepies
    Free Member

    See above 🙂

    flanagaj
    Free Member

    I’ll get my coat! 🙂

    mrjmt
    Free Member

    Ah! Sorry, not paying enough attention! printf works a treat.

    Eeh when I were a lad it were just

    10 PRINT “hello world!
    20 GOTO 10

    Thanks very much.

    🙂

Viewing 8 posts - 1 through 8 (of 8 total)

The topic ‘A little Java help please, printing float array values to 2 DP’ is closed to new replies.