Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 the correct value of "15000.0". However, I want to display the value to the front end user as just "15000", so just want to remove the decimal and any preceding values thereafter. How can this be done? My code is below:

float HouseValue = 150000; double percentageValue;  percentageValue = calculateStampDuty(10, HouseValue);  private double calculateStampDuty(int PercentageIn, double HouseValueIn){     double test = PercentageIn * HouseValueIn / 100;     return test; } 

I have tried the following:

  • Creating a new string which will convert the double value to a string, as per below:

    String newValue = percentageValue.toString();

  • I have tried using the 'valueOf' method on the String object, as per below:

    String total2 = String.valueOf(percentageValue);

However, I just cannot get a value with no decimal places. Does anyone know in this example how you would get "15000" instead of "15000.0"?

Thanks

like image 847
Sudhir Avatar asked Sep 27 '13 21:09

Sudhir


People also ask

How do I stop decimal values in Java?

You can use integer if you don't want decimals at all, if you just don't want decimal format when you have an integer then DecimalFormat should work. Using a float for a currency value is your first problem. Use BigDecimal instead - binary floating point isn't suitable for "manmade" values like currency.

How do you limit the decimal place of a double in Java?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places.


2 Answers

Nice and simple. Add this snippet in whatever you're outputting to:

String.format("%.0f", percentageValue) 
like image 154
Chris Avatar answered Sep 21 '22 11:09

Chris


You can convert the double value into a int value. int x = (int) y where y is your double variable. Then, printing x does not give decimal places (15000 instead of 15000.0).

like image 31
C-Otto Avatar answered Sep 24 '22 11:09

C-Otto