-
Format Specifiers
Hi everyone,
I hope someone can help me. I'm writing a program for a college assignment that needs to handle numbers in millions like 5,550,000. I'v declared the variable to hold them as type long, but the only way I can get the numbers into a printf statement is to use the format specifier %.2f. This works fine but the only problem is the number has 2 decimal points that I dont want to be there because they will always be 0's. Does anyone know if there is a specific format specifier for long as %d wont work either.
Thank you.
-
printf ( " %d ", longValue);
also you might want to consider BigIntegers.
-
Two common ways to do this are the String.format / printf group of methods (and use as noted above %d will work for longs) or you could create a DecimalFormat instance. Both ways will allow strings to be shown with or without groupings:
Code:
import java.text.DecimalFormat;
public class Fu1 {
public static void main(String[] args) {
long myLong = 1234567890123L;
DecimalFormat dfWithGrouping = new DecimalFormat("00");
dfWithGrouping.setGroupingSize(3);
dfWithGrouping.setGroupingUsed(true);
System.out.print("With Grouping: ");
System.out.println(dfWithGrouping.format(myLong));
DecimalFormat dfWithOutGrouping = new DecimalFormat("00");
System.out.print("Without Grouping: ");
System.out.println(dfWithOutGrouping.format(myLong));
System.out.println();
System.out.printf("With Grouping: %,d %n", myLong);
System.out.printf("Without Grouping: %d %n", myLong);
}
}
-
Thanks
Thanks for the help guys my code is working perfectly now.