Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

padding longs

I am doing some math using longs which will yield numbers like 5, 10, 20, etc
but I always need to pad the result to be 3 digits.
What's the best way to do that?
0
dpalyca755
Asked:
dpalyca755
  • 3
  • 3
3 Solutions
 
CPColinCommented:
Using zeros in a DecimalFormat will work:

new DecimalFormat("000").format(x);

Open in new window

0
 
wdosanjosCommented:
Use the DecimalFormat class.  Here is an example:
import java.text.*;

public class Test
{
    public static void main(String args[])
    {
        DecimalFormat formatter = new DecimalFormat("000");
        long nbr = 50;

        String fmt_nbr = formatter.format(nbr);

        System.out.println(fmt_nbr);
        
        /*
        
        Output:
        
        050
        
        */
     }
}

Open in new window

0
 
dpalyca755Author Commented:
Can I use the String Format method to do so?
What is the syntax if do so?
let's say the 5 I referenced earlier is stored in the variable myString.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
CPColinCommented:
Assuming you have a long, it would be something like this:

String.format("%03d", myLong);

Open in new window


The "0" means "pad with zeros," the "3" means "make the output three characters wide," and the "d" means "output a number."
0
 
dpalyca755Author Commented:
I can't compile that for some reason.
I tried that exact line too.
What am I doing wrong?

Code Snippet:
long c = 5;
String pad2 = String.format("%03d", c);        
---------------------------------------------------------------------------
Error:
test.java:51: cannot resolve symbol
symbol  : method format (java.lang.String,long)
location: class java.lang.String
             String pad2 = String.format("%03d", c);
                                 ^
1 error
0
 
CPColinCommented:
I've only seen that happen when using a version of Java older than 1.5 or when I've told the compiler to pretend like its from an old version of Java. Do you know if that's happening?
0
 
dpalyca755Author Commented:
Yup....I was accidentally pointing to an older version.
I fixed it.  Works now.
Thanks.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now