How to store decimal value in java

Having the following code in Java:

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

Result: 0.0

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

+3
source share
7 answers

Initialize your variable with an expression that evaluates to double, not int:

double operation = 890.0 / 1440.0;

Otherwise, the expression is executed using integer arithmetic (which ends with truncating the result). This truncated result is then converted to double.

+14
source

You can use a double literal d- otherwise your numbers will be considered like int:

double operation = 890d / 1440d;

NumberFormat, .

:

NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
+7

- :

double result = (double) 890 / 1400;

:

0,6180555555555556

,

+5

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));
        }
    }

: 0.6180555555555556 : 0,6181

+2

BigDecimal, , :

    BigDecimal first = new BigDecimal(890);
    BigDecimal second = new BigDecimal(1440);
    System.out.println(first.divide(second, new MathContext(4, RoundingMode.HALF_EVEN)));
+2

4 , , , f :

long fractionalPart = 10000L * 890L / 1440L;

, , 32 .

0
double operation = 890.0 / 1440;
System.out.printf(".4f\n", operation);
0

Source: https://habr.com/ru/post/1752892/


All Articles