Java - Write code to Format input numbers

Requirement

Write a program that reads 3 numbers

  • an integer a (0 = a = 500)
  • a floating-point b and
  • a floating-point c and prints them in 4 virtual columns on the console.

Each column should have a width of 10 characters.

The number a should be printed in hexadecimal, left aligned.

Then the number a should be printed in binary form, padded with zeroes, then the number b should be printed with 2 digits after the decimal point, right aligned;

The number c should be printed with 3 digits after the decimal point, left aligned.

Demo

import java.util.Locale;

public class Main {
  public static void main(String[] args) {
    Locale.setDefault(Locale.ROOT);
    int numA = 123;
    double numB = 123.456;
    double numC = 234234.234234;

    System.out.print("|");
    System.out.printf("%-10X|", numA); // first col --> HEX

    String binString = Integer.toBinaryString(numA);
    while (binString.length() < 10) { // pad with 10 0's
      binString = "0" + binString;
    }//from  ww  w . ja v a  2s . co  m
    System.out.printf("%S|", binString); // second col --> BIN

    System.out.printf("%10.2f|", numB); // third col

    System.out.printf("%-10.3f|", numC); // fourth col

  }
}

Related Topic