Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double value with specific precision in java

Tags:

java

double

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");
like image 938
Mehrdad Salimi Avatar asked Sep 22 '13 17:09

Mehrdad Salimi


People also ask

What is the precision of double in Java?

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.

How do you specify a double in Java?

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.


1 Answers

System.out.format("%.4f kg\n", 0.0d) prints '0.0000 kg'

like image 88
Marc Dzaebel Avatar answered Sep 16 '22 15:09

Marc Dzaebel