How to remove decimal values from a value of type 'double' in Java

后端 未结 19 1774
孤独总比滥情好
孤独总比滥情好 2020-12-08 09:26

I am invoking a method called \"calculateStampDuty\", which will return the amount of stamp duty to be paid on a property. The percentage calculation works fine, and returns

相关标签:
19条回答
  • 2020-12-08 09:42

    With a cast. You're basically telling the compiler "I know that I'll lose information with this, but it's okay". And then you convert the casted integer into a string to display it.

    String newValue = ((int) percentageValue).toString();
    
    0 讨论(0)
  • 2020-12-08 09:44
    Double i = Double.parseDouble("String with double value");
    
    Log.i(tag, "display double " + i);
    
    try {
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMaximumFractionDigits(0); // set as you need
        String myStringmax = nf.format(i);
    
        String result = myStringmax.replaceAll("[-+.^:,]", "");
    
        Double i = Double.parseDouble(result);
    
        int max = Integer.parseInt(result);
    } catch (Exception e) {
        System.out.println("ex=" + e);
    }
    
    0 讨论(0)
  • 2020-12-08 09:44

    Use Math.Round(double);

    I have used it myself. It actually rounds off the decimal places.

    d = 19.82;
    ans = Math.round(d);
    System.out.println(ans);
    // Output : 20 
    
    d = 19.33;
    ans = Math.round(d);
    System.out.println(ans);
    // Output : 19 
    

    Hope it Helps :-)

    0 讨论(0)
  • 2020-12-08 09:48

    You can convert double,float variables to integer in a single line of code using explicit type casting.

    float x = 3.05
    int y = (int) x;
    System.out.println(y);
    

    The output will be 3

    0 讨论(0)
  • 2020-12-08 09:50

    The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
    To get a double value as string with no decimals use the code below.

    DecimalFormat decimalFormat = new DecimalFormat(".");
    decimalFormat.setGroupingUsed(false);
    decimalFormat.setDecimalSeparatorAlwaysShown(false);
    
    String year = decimalFormat.format(32024.2345D);
    
    0 讨论(0)
  • 2020-12-08 09:51

    Alternatively, you can use the method int integerValue = (int)Math.round(double a);

    0 讨论(0)
提交回复
热议问题