77

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

6
  • 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. Sep 27, 2013 at 21:36
  • 7
    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.
    – Jon Skeet
    Sep 27, 2013 at 21:36
  • @JonSkeet Or just an int amount of cents.
    – tckmn
    Sep 27, 2013 at 21:37
  • @Doorknob: Potentially - but personally I'd rather use a type that meant I didn't have to remember that everywhere I used it. It depends on the context though, agreed.
    – Jon Skeet
    Sep 27, 2013 at 21:38
  • int for cents works if you know you're only ever going to be dealing with whole cents, and not fractions of a cent. Ever. Sep 27, 2013 at 21:40

21 Answers 21

90

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

String.format("%.0f", percentageValue)
2
  • 4
    4.6 -> 5, 3.4 -> 3 I think it rounds the number up, not remove the numbers after the period.
    – Marlon
    Feb 12, 2019 at 18:50
  • String.format is the slowest way to do this according to here.
    – Siddhartha
    May 8, 2019 at 0:33
52

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).

9
  • 74
    typecast to int is not advisable as your double may be beyond the range int supports Dec 1, 2014 at 20:06
  • 2
    How is this the answer? I get a compilation error says that you cannot cast a double to an int. May 1, 2015 at 22:46
  • @C-Otto I just did it in Java6 and Java7 double dbtest = 1.0; int inttest = (int)dbtest; inconvertible types. What am I doing wrong then? May 7, 2015 at 12:22
  • 2
    Nevermind @C-Otto Doornob found that I was using Double instead of double. Thanks for correcting me though. May 7, 2015 at 12:43
  • 1
    raghavsood33 casting to int is okay so long as you are willing to forgo your precision. However, don't do this if you work for NASA rocket systems.
    – F.O.O
    Jan 3, 2016 at 23:19
50

I did this to remove the decimal places from the double value

new DecimalFormat("#").format(100.0);

The output of the above is

100

1
  • 1
    This works. At the cost of having to change my return type into a String.
    – Ndivhuwo
    Aug 5, 2019 at 13:31
16

You could use

String newValue = Integer.toString((int)percentageValue);

Or

String newValue = Double.toString(Math.floor(percentageValue));
7
  • 1
    How do you call toString() on a primitive?
    – FDinoff
    Sep 27, 2013 at 22:20
  • cannot cast a double to an int. May 1, 2015 at 22:46
  • @Doorknob Yes, I just did it in Java6 and Java7 double dbtest = 1.0; int inttest = (int)dbtest; inconvertible types. What am I doing wrong then? May 7, 2015 at 12:20
  • @AbuSulaiman Post your entire code here then (with pastebin.com for example), because something else is wrong and the cast is not the problem.
    – tckmn
    May 7, 2015 at 12:24
  • 1
    @AbuSulaiman Haha, no problem. I've spent far longer on far more obvious bugs before. :)
    – tckmn
    May 7, 2015 at 12:41
10

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

5

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]);
1
  • 3
    String.valueOf not advisable as your double can com out to be in exponential/scentific notation e.g., 9.99999E11 Dec 1, 2014 at 20:06
5

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));
5
Double d = 1000d;
System.out.println("Normal value :"+d);
System.out.println("Without decimal points :"+d.longValue());
0
4

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 :-)

4

the simple way to remove

new java.text.DecimalFormat("#").format(value)
2

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

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();
2
  • 2
    typecast to int is not advisable as your double may be beyond the range int supports Dec 1, 2014 at 20:06
  • toString() on primitive int not possible.
    – F.O.O
    Jan 3, 2016 at 23:16
1

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

1
  • 2
    DecimalFormat rounds and not truncates Dec 1, 2014 at 20:43
1

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.
1

Type casting to integer may create problem but even long type can not hold every bit of double after narrowing down to decimal places. If you know your values will never exceed Long.MAX_VALUE value, this might be a clean solution.

So use the following with the above known risk.

double mValue = 1234567890.123456;
long mStrippedValue = new Double(mValue).longValue();
1

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

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

declare a double value and convert to long convert to string and formated to float the double value finally replace all the value like 123456789,0000 to 123456789

Double value = double value ;
Long longValue = value.longValue();  
String strCellValue1 = new String(longValue.toString().format("%f",value).replaceAll("\\,?0*$", ""));
0
    public class RemoveDecimalPoint{

         public static void main(String []args){
            System.out.println(""+ removePoint(250022005.60));
         }
 
       public static String  removePoint(double number) {        
            long x = (long) number;
            return x+"";
        }

    }
3
  • Wouldn't casting number to a long already remove the decimal portion of the number? Nov 17, 2020 at 13:08
  • it required to prevent a Round of value and get an actual number when used only NumberFormat then output is 250022006 but I jut remove .60 and need to 250022005 Nov 19, 2020 at 8:16
  • So yes... I am asking because the NumberFormat is not needed when the number has already been truncated. Nov 19, 2020 at 11:23
0

This should do the trick.

System.out.println(percentageValue.split("\\.")[0]);
-1

Try:

String newValue = String.format("%d", (int)d);
1
  • 2
    typecast to int is not advisable as your double may be beyond the range int supports Dec 1, 2014 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.