java float format specifier code example

Example 1: java printf format string and int

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
                //Complete this line                
                System.out.printf("%-15s%03d%n",s1,x);
            }
            System.out.println("================================");

    }
}

Example 2: float format decimal places

num = 1.234
print("{:.2f}".format(num))
>> 1.23

print(f"{num:.2f}")
>> 1.23

Tags:

Misc Example