In my printf
, I need to use %f
but I\'m not sure how to truncate to 2 decimal places:
Example: getting
3.14159
Use this
printf ("%.2f", 3.14159);
System.out.printf("%.2f", number);
BUT, this will round the number to the nearest decimal point you have mentioned.(As in your case you will get 3.14 since rounding 3.14159 to 2 decimal points will be 3.14)
Since the function printf will round the numbers the answers for some other numbers may look like this,
System.out.printf("%.2f", 3.14136); -> 3.14
System.out.printf("%.2f", 3.14536); -> 3.15
System.out.printf("%.2f", 3.14836); -> 3.15
If you just need to cutoff the decimal numbers and limit it to a k
decimal numbers without rounding,
lets say k = 2.
System.out.printf("%.2f", 3.14136 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14536 - 0.005); -> 3.14
System.out.printf("%.2f", 3.14836 - 0.005); -> 3.14