- Your last format specifier should be an
f
for floating point number using width and precision numbers: e.g.,%20.5f
- Many of your String specifiers,
%xs
, should likely be decimal specifiers,%xd
wherex
is the format width. - If you make this change, then the corresponding argument should be a decimal number, not a String.
- You have too many format specifiers for the number of arguments you pass in. This is nothing but basic math. Count your specifiers and your parameters.
- Read the Formatter API for all the details.
using printf for mixed multiple formats
-
05-08-2022 - |
Question
I have a question on how I am supposed to use printf for a mix of multiple formats. In my case, I am trying to give a number a certain amount of spaces so that it fits perfectly In a table and I am trying to limit how many decimal places it is allowed. Below is what I have tried with printf:
System.out.printf("%1s%10s%27s%26s%28s%28s1.5d", typeOCar, startingMiles, endingMiles, Distance, gallons, MPG);
when I execute my program, it displays this:
run:
Gas & Mileage Calculations
Car Type Starting Miles Ending Miles Distance Gallons Miles/Gallon
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Toyota Sequoia 15543 15565 22 16.5 1.33333333333333331.5dBUILD SUCCESSFUL (total time: 0 seconds)
Any help will be greatly appreciated.
La solution
Autres conseils
import java.text.DecimalFormat;
then use this in your code:
DecimalFormat fmt = new DecimalFormat("00.##"); //0 = numbers before . and # numbers after .
and to convert any value (example here being printed out directly):
System.out.println(fmt.format(varName));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow