A little Java help ...
 

  You don't need to be an 'investor' to invest in Singletrack: 6 days left: 95% of target - Find out more

[Closed] A little Java help please, printing float array values to 2 DP

7 Posts
3 Users
0 Reactions
67 Views
Posts: 2053
Free Member
Topic starter
 

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!


 
Posted : 03/04/2017 12:34 pm
Posts: 1510
Free Member
 

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


 
Posted : 03/04/2017 12:52 pm
Posts: 2053
Free Member
Topic starter
 

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


 
Posted : 03/04/2017 12:59 pm
Posts: 0
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


 
Posted : 03/04/2017 12:59 pm
Posts: 2053
Free Member
Topic starter
 

Edit for your edit (!)

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


 
Posted : 03/04/2017 1:02 pm
Posts: 0
Free Member
 

See above 🙂


 
Posted : 03/04/2017 1:04 pm
Posts: 1510
Free Member
 

I'll get my coat! 🙂


 
Posted : 03/04/2017 1:07 pm
Posts: 2053
Free Member
Topic starter
 

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.

🙂


 
Posted : 03/04/2017 1:08 pm

6 DAYS LEFT
We are currently at 95% of our target!