Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 784
jmasterx Avatar asked Aug 25 '11 20:08

jmasterx


People also ask

How do I print 2 digits after a decimal?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.

How do you print floating numbers up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

What is .2f in Java?

2f", val); In short, the %. 2f syntax tells Java to return your variable ( val ) with 2 decimal places ( . 2 ) in decimal representation of a floating-point number ( f ) from the start of the format specifier ( % ).

How many numbers can print after a point using 2f?

2f gives the value upto 2 digits after decimal.


2 Answers

Use this:

printf ("%.2f", 3.14159);
like image 143
Kevin Avatar answered Oct 20 '22 02:10

Kevin


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"
like image 16
Alexis King Avatar answered Oct 20 '22 02:10

Alexis King