I have different types of numbers of type float and/or double.
I want to set these numbers to a specific format of 6 digits.
Examples:
1.01234
10.1234
101.234
1012.34
10123.4
101234
1.10000
1.33000
Regardless of how a number looks, whether is has a a decimal or it doesn’t, I want it to be 6 digits.
So I have:
String s = "123.4";
I want printout to look like: 123.400
I know I can use String.format("%.3f", s)
to get result of type xxx.xxx
But what if have a different number?
Check the examples below and required results:
123456 to 123456
1.2 to 1.20000
0.56 to 0.56000
0.001 to 0.00100
Note that the required result has 6 digits.
2
Answers
You could use the DecimalFormat class to format your numbers, then maybe switch on the length of your number and play with the
setMinimumFractionDigits
,setMaximumFractionDigits
,setMinimumIntegerDigits
andsetMaximumIntegerDigits
methods to format your number with the number of leading and trailing zeros you want.You can use
Math.log10(double)
to discover how many digits are in the number. Create a variable format specifier using the result:Results:
This code has some known shortcomings:
NumberFormatException
if the value is1_000_000.0
or greater or is zero.