Number of digits after decimal using String.format - java

I know to convert a double value to string , I can do like this :
String value = String.format("%f", 10.0000);
Also I can control the number of digits after decimal using this :
String value = String.format("%.3f", 10.000000);
But my problem is that, I am receiving number of digits after decimal point through a variable.
How can I use String.format to print the number of digits after decimal provided by the user.
Regards,
Anuj

String value = String.format("%."+x+"f", 10.000000);
where x is number of digits.

Related

How to print entire number even after removing decimal point?

I have a number as
Double d = 100.000000;
I want to remove the decimal point and print the values as 100000000
(Note I am using java)
It is impossible. double doesn't store zeroes after decimal point so 1.0000 is equal to 1.0.
Hint: you can use BigDecimal for this. It have scale.
I'm afraid 100.000000 does not equal 100000000 and as mentioned by #talex, double doesn't store the zeros after the decimal point.
Your best bet is to use a String and remove the . manually:
String s = "100.000000";
System.out.println(s.replaceAll("\\.", "")); //note '.' needs to be escaped
Output:
100000000
You could parse it as a Double then if necessary.
Format the value using String.format and the remove the separator.
double d = 100.000;
String formatted = String.format(
Locale.US, //Using a Locale US to be sure the decimal separator is a "."
"%5f", //A decimal value with 5decimal
d) //The value to format
.replace(".", ""); //remove the separator
System.out.println(formatted);
100000000
Other examples :
100.000123456 > 100000123
You can see that the value is truncated, it is important to understand that.
Note that I have set the String to have 5 decimal number, but this up to you.
the double does not store the number as 100.0000 it just stored as 100.0 that means any unnecessary zeros on the right will be deleted but if the number was like this 100.01234 u can use this trick
Double d = 100.01245;
String text = Double.toString(d);
text.replace(".","");
d = Double.parseDouble(text);
or u can store the number as sting from the beginning
String text = "100.000000";
d.replace(".","");
double d = Double.parseDouble(text);

Format a number stored as a String

I have a String that represents an amount of money passed from input that will optionally contain a decimal point and trailing zeros. It can look like any of these:
inputA = "123.45"
inputB = "123"
inputC = "123.4"
inputD = ".50"
Is there a way to convert these so that they all have the format 0.00 with at least one digit to the left of the decimal point and exactly two to the right without having to convert to a number object like BigDecimal and then back?
You can use DecimalFormat to achieve formatting.
DecimalFormat format = new DecimalFormat("##0.00");
System.out.println(format.format(10));
Output : 10.00
Tricks:
String formattedDouble=String.format("%.2f", Double.valueOf(strDouble));
And, %.2f will format your double as 1.00, 0.20 or 5.21. Double.valueOf(strDouble) convert your String double into a double.

What is the difference between these 2 String formatting?

value
double value = 345.12345;
String Format 1
String str = String.format("%.02f", value);
String Format 2
String str = String.format("%.2f", value);
Both print the same value 345.12. So, what is the difference between these two?
The 0 prefix notation only works for the integer part, not the decimal part. If you had say %07.2f instead, it would show the value as 0345.12.
The syntax for a format specifier is
%[argument_index$][flags][width][.precision]conversion
Note that precision is 02 in the first case and 2 in the second case, but since these are the same number, the output is the same. Hence "%.02f" and "%.2f" are the same.
But, if you had written %02f, then flags would be 0 ("zero-pad output up to width") and width would be 2. Then the output would be zero-padded up to the specified width.

DecimalFormat pattern

public static String formatAmountUpToTwoDecimalNumber(String amount)
{
if(amount==null || "".equals(amount))
{
return "";
}
Double doubleAmount = Double.valueOf(amount);
double myAmount = doubleAmount.doubleValue();
NumberFormat f = new DecimalFormat("###,###,###,###,##0.00");
String s = f.format(myAmount);
return s;
}
"###,###,###,###,##0.00", What exactly is the purpose of this pattern ? I believe it serves two purposes
to group numbers, that is put thousand seperator comma
to append two zeros after decimal if decimal is missing that is convert 23 to 23.00
But why there is "0" instead of "#" before decimal? what exactly is the purpose of this zero?
Thanks for the help.
Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
From: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
So # is not shown when there is no number. The leading 0 means there will be at least 1 digit before the decimal separator.
# will put a digit only if it is not a leading zero. 0 will put a digit even if it is a trailing zero. You could use zeros in front, too, if you wanted a fixed number of digits printed.
With the zero before the dp, small numbers like 0.23 will be displayed as 0.23. Without it you will not get the leading zero, so it is just displayed as .23. If you have a spreadsheet like excel you can check this there too.

Java: string tokenizer and assign to 2 variables?

Let's say I have a time hh:mm (eg. 11:22) and I want to use a string tokenizer to split. However, after it's split I am able to get for example: 11 and next line 22. But how do I assign 11 to a variable name "hour" and another variable name "min"?
Also another question. How do I round up a number? Even if it's 2.1 I want it to round up to 3?
Have a look at Split a string using String.split()
Spmething like
String s[] = "11:22".split(":");;
String s1 = s[0];
String s2 = s[1];
And ceil for rounding up
Find ceiling value of a number using Math.ceil
Rounding a number up isn't too hard. First you need to determine whether it's a whole number or not, by comparing it cast as both an int and a double. If they don't match, the number is not whole, so you can add 1 to the int value to round it up.
// num is type double, but will work with floats too
if ((int)num != (double)num) {
int roundedNum = (int)num + 1;
}

Categories

Resources