Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a 3-digit integer to a 4-digit string? [duplicate]

Tags:

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!

like image 917
Melvin Lai Avatar asked Jul 17 '13 10:07

Melvin Lai


People also ask

How do you add leading zeros to integers?

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.

How do you print a 3 digit number in Python?

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.


2 Answers

Use String#format:

String b = String.format("%04d", a); 

For other formats refer the documentation

like image 146
Thilo Avatar answered Sep 22 '22 08:09

Thilo


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

like image 34
Jost Avatar answered Sep 19 '22 08:09

Jost