Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 303
  • 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
 
CPColinSenior Java ArchitectCommented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
CPColinSenior Java ArchitectCommented:
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
 
CPColinSenior Java ArchitectCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

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