Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how %f works in java

I saw %f mostly in tow different occasions. first, in printf which [I think] I know the usage but not the logic:

System.out.printf("%.2f", 3.1415); // will print 2 digits after decimal!

and also for formatting floats like in nextFloat() random generator which I neither know the usage nor the logic behind:

Random random1 = new Random(100);
float g0 = Math.abs(random1.nextFloat()); // 0.7220096
float g1 = Math.abs(random1.nextFloat() %.1f); // 0.0346627
float g2 = Math.abs(random1.nextFloat() %1f); // 0.19497603
float g3 = Math.abs(random1.nextFloat()) %1f; // 0.7158033

I googled to find some explanation but I wasn't sure which category I should search. (is this a regular expression or flag ... ?) Can somebody give me some example and explain how it works exactly?

like image 784
Yar Avatar asked Mar 18 '23 18:03

Yar


1 Answers

That's not a formatting issue - you're calculating modulus!

like image 67
Nir Alfasi Avatar answered Mar 27 '23 16:03

Nir Alfasi