[Q#2538787][A#2538803] How to display an output of float data with 2 decimal places in Java?
https://stackoverflow.com/q/2538787
Can I do it with System.out.print?
Answer
https://stackoverflow.com/a/2538803
You can use the printf method, like so: 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 (%). There are other conversion characters you can use besides f:
APIzation
System.out.printf("%.2f", val);
package com.stackoverflow.api;
public class Human2538803 {
public static void printFloatWithTwoDecimals(float val) {
System.out.printf("%.2f", val);
}
}
package com.stackoverflow.api;
/**
* How to display an output of float data with 2 decimal places in Java?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/2538803">https://stackoverflow.com/a/2538803</a>
*/
public class APIzator2538803 {
public static void displayOutput(int val) throws Exception {
System.out.printf("%.2f", val);
}
}