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

后端 未结 19 1775
孤独总比滥情好
孤独总比滥情好 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:54

    Try this you will get a string from the format method.

    DecimalFormat df = new DecimalFormat("##0");
    
    df.format((Math.round(doubleValue * 100.0) / 100.0));
    
    0 讨论(0)
  • 2020-12-08 09:56

    You can use DecimalFormat, but please also note that it is not a good idea to use double in these situations, rather use BigDecimal

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

    String truncatedValue = String.format("%f", percentageValue).split("\\.")[0]; solves the purpose

    The problem is two fold-

    1. To retain the integral (mathematical integer) part of the double. Hence can't typecast (int) percentageValue
    2. Truncate (and not round) the decimal part. Hence can't use String.format("%.0f", percentageValue) or new java.text.DecimalFormat("#").format(percentageValue) as both of these round the decimal part.
    0 讨论(0)
  • 2020-12-08 09:59

    I would try this:

    String numWihoutDecimal = String.valueOf(percentageValue).split("\\.")[0];
    

    I've tested this and it works so then it's just convert from this string to whatever type of number or whatever variable you want. You could do something like this.

    int num = Integer.parseInt(String.valueOf(percentageValue).split("\\.")[0]);
    
    0 讨论(0)
  • 2020-12-08 09:59
    Double d = 1000d;
    System.out.println("Normal value :"+d);
    System.out.println("Without decimal points :"+d.longValue());
    
    0 讨论(0)
  • 2020-12-08 09:59

    Try:

    String newValue = String.format("%d", (int)d);
    
    0 讨论(0)
提交回复
热议问题