I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string. Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.
For example for these input, output will be:
1 kg
output:2.2046
3.1 kg
output:6.8343
But when the input is 0, the output should be 0.0000, but it shows 0.0 . What should I do to force it to show 0.0000?
I read similar post about double precision, they suggest something like BigDecimal
class, but I can't use them in this case,
my code for doing this is:
line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");
The double data type is a 64-bit double-precision IEEE 754 floating-point number. It means that it gives 15-16 decimal digits precision. It consumes more memory in comparison to the float data type. It is used to store decimal values.
From the Java language Specification: A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
System.out.format("%.4f kg\n", 0.0d)
prints '0.0000 kg'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With