I wrote this code:
double sums = Math.round(sum) * 100.00 / 100.00;
I am only getting one 0
after the decimal (e.g. 10.0
) but I want 10.00
.
Is there something wrong ?
I wrote this code:
double sums = Math.round(sum) * 100.00 / 100.00;
I am only getting one 0
after the decimal (e.g. 10.0
) but I want 10.00
.
Is there something wrong ?
I suspect you intended
double sums = Math.round(sum * 100) / 100.0;
This will round the number to 2 decimal places.
I am only getting one 0 after the decimal (e.g. 10.0) but I want 10.00.
The number 10.0
== 10.00
and there is no difference except the formatting. You can format the String and round it at the same time.
double sum = 9.999;
String fmt = String.format("%.2f", sum);
// fmt = "10.00"
A number is just a numebr, it has no inherent format.
Use String.format
to be sure you get it only the number of digit you wanted
For Example if i write
public static void main(String[] args) {
double sum=23.90;
double sums = Math.round(sum * 100) / 100.0;
System.out.println(sums);
}
It will give me output
upto one decimal point
i.e 23.9
but if i change the same code to
public static void main(String[] args) {
double sum=23.945;
double sums = Math.round(sum * 100) / 100.0;
System.out.println(sums);
}
I get output to two decimal Point i.e
23.95
But with String format you will be always sure how many decimal you are going to print
public static void main(String[] args) {
double sum=23.945;
double sums = Math.round(sum * 100) / 100.0;
String fmt = String.format("%.1f", sums);
System.out.println(fmt);
}
Output 24.0 .. But it has got the problem of rounding So better Practice is to use first convert it into String and then trim the Characters