printf %f with only 2 numbers after the decimal point?

Java

Java Problem Overview


In my printf, I need to use %f but I'm not sure how to truncate to 2 decimal places:

Example: getting

3.14159

to print as:

3.14

Java Solutions


Solution 1 - Java

Use this:

printf ("%.2f", 3.14159);

Solution 2 - Java

You can use something like this:

printf("%.2f", number);

If you need to use the string for something other than printing out, use the NumberFormat class:

NumberFormat formatter = new DecimalFormatter("#.##");
String s = formatter.format(3.14159265); // Creates a string containing "3.14"

Solution 3 - Java

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

Solution 4 - Java

Try:

printf("%.2f", 3.14159);

Reference:

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Solution 5 - Java

as described in Formatter class, you need to declare precision. %.2f in your case.

Solution 6 - Java

Use this

printf ("%.2f", 3.14159);

Solution 7 - Java

You can try printf("%.2f", [double]);

Solution 8 - Java

I suggest to learn it with printf because for many cases this will be sufficient for your needs and you won't need to create other objects.

double d = 3.14159;     
printf ("%.2f", d);

But if you need rounding please refer to this post

https://stackoverflow.com/a/153785/2815227

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjmasterxView Question on Stackoverflow
Solution 1 - JavaKevinView Answer on Stackoverflow
Solution 2 - JavaAlexis KingView Answer on Stackoverflow
Solution 3 - JavaprimeView Answer on Stackoverflow
Solution 4 - JavaBillView Answer on Stackoverflow
Solution 5 - JavaMichał ŠrajerView Answer on Stackoverflow
Solution 6 - JavaSibbs GamblingView Answer on Stackoverflow
Solution 7 - JavaLior OhanaView Answer on Stackoverflow
Solution 8 - JavamcvkrView Answer on Stackoverflow