I am trying to multiply 1207.87 by 10000 and expecting 12078700.0 but I am getting 1.2078699999999998E7
I understand that its related to precision mistake but how do i rectify this problem
EDIT:-
I simply want to remove the decimal
I am trying to multiply 1207.87 by 10000 and expecting 12078700.0 but I am getting 1.2078699999999998E7
I understand that its related to precision mistake but how do i rectify this problem
EDIT:-
I simply want to remove the decimal
This is because of float numbers representation.
You can:
Math.round(...)
More about What Every Computer Scientist Should Know About Floating-Point Arithmetic.
You need to do the CAST:
(int) 1207.87 * 10000
You cannot rectify this if you use double
type. You can if you use BigDecimal
.
Try to use decimal format like:
DecimalFormat f = new DecimalFormat("#0.00");
f.format(Double.valueOf(yourDouble));
Hope this can help you!
double are stored in exponental precision in java and many other languages. see IEEE754for more information about float, double and their variant
If you want a integer result, then cast your floating point number, or the result. If you want to just print a floating number in "ordinary notation", then you can use the class NumberFormat
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(4.0));
example taken from here
finally you can use a fixed precision number with the class BigDecimal, but please take care that this is normally not hardware (FPU) accelerated so will slow down a lot your calculation, but will give you fixed error. That kind of number is especially used in simulation where error must be know
You can use formatted output as below:
double ans = 1207.87 * 10000;
System.out.printf("ans: %.0f\n", ans);
Output:
ans: 12078700
Simple way would be this one:
Double j = 1207.87;
int x = j.intValue();
System.out.println(x * 10000);