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
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.
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 %.
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 ( % ).
2f gives the value upto 2 digits after decimal.
Use this:
printf ("%.2f", 3.14159);
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With