Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save decimal in java

Tags:

java

math

Having the following code in Java:

double operation = 890 / 1440;  
System.out.println(operation);  

Result: 0.0

What I want is to save the first 4 decimal digits of this operation (0.6180). Do you know how can I do it?

like image 756
Eric Avatar asked Jul 02 '10 19:07

Eric


People also ask

How are decimals stored in Java?

A float data type in Java stores a decimal value with 6-7 total digits of precision. So, for example, 12.12345 can be saved as a float, but 12.123456789 can't be saved as a float. When representing a float data type in Java, we should append the letter f to the end of the data type; otherwise it will save as double.

How do you store decimal values?

The significant digits to the left of the decimal and the significant digits to the right of the decimal are stored in separate groups of bytes. At the maximum precision specification, DECIMAL(32,s) data types can store s-1 decimal digits to the right of the decimal point, if s is an odd number.

What is .2f in Java?

The %. 2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).


4 Answers

This is done using BigDecimal

   import java.math.BigDecimal;
import java.math.RoundingMode;


    public class DecimalTest {

        /**
         * @param args
         */
        public static void main(String[] args) {
            double operation = 890.0 / 1440.0;
            BigDecimal big = new BigDecimal(operation);     
            big = big.setScale(4, RoundingMode.HALF_UP);        
            double d2 = big.doubleValue();
            System.out.println(String.format("operation : %s", operation));
            System.out.println(String.format("scaled : %s", d2));
        }
    }

Output

operation : 0.6180555555555556 scaled : 0.6181

like image 78
Greg Avatar answered Oct 12 '22 23:10

Greg


Initialize your variable with an expression that evaluates to a double rather than an int:

double operation = 890.0 / 1440.0;

Otherwise the expression is done using integer arithmetic (which ends up truncating the result). That truncated result then gets converted to a double.

like image 27
Michael Burr Avatar answered Oct 13 '22 00:10

Michael Burr


You can use the double literal d - otherwise your numbers are considered of type int:

double operation = 890d / 1440d;

Then you can use a NumberFormat to specify the number of digits.

For example:

NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
like image 26
Bozho Avatar answered Oct 13 '22 01:10

Bozho


You can also do something like this:

double result = (double) 890 / 1400;

which prints the following:

0.6180555555555556

You can check how to round up the number here

like image 29
npinti Avatar answered Oct 13 '22 00:10

npinti