I would like to format a 3-digit integer
to a 4-digit string
value. Example:
int a = 800; String b = "0800";
Of course the formatting will be done at String b
statement. Thanks guys!
You can add leading zeros to an integer by using the "D" standard numeric format string with a precision specifier. You can add leading zeros to both integer and floating-point numbers by using a custom numeric format string.
Get input num from user using input() method check whether the num is greater than 99 and less than 100 using if statement. if it is true, then print num is three digit number using print() method. Else print num is not three digit number using print() method.
Use String#format:
String b = String.format("%04d", a);
For other formats refer the documentation
If you want to have it only once use String.format("%04d", number)
- if you need it more often and want to centralize the pattern (e.g. config file) see the solution below.
Btw. there is an Oracle tutorial on number formatting.
To make it short:
import java.text.*; public class Demo { static public void main(String[] args) { int value = 123; String pattern="0000"; DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(output); // 0123 } }
Hope that helps. *Jost
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