theJava
theJava

Reputation: 15034

Removing decimals from the numbers

public static String convertCentimeterToHeight(double d) {
    double feetPart = 0;
    double inchesPart = 0;
    if (String.valueOf(d) != null && String.valueOf(d).trim().length() != 0) {
        feetPart = (int) Math.floor((d / 2.54) / 12);
        inchesPart = (int) Math.ceil((d / 2.54) - (feetPart * 12));
    }
    return (String.valueOf(feetPart)) + "' " + String.valueOf(inchesPart) + "''";
}

I am trying to remove decimals, but i am still getting something like this 5.0' 6.0". When we do a String.value() on a variable does it remove the decimals and give me the exact number?

Upvotes: 0

Views: 278

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533500

For your information.

// always true, it never returns null
String.valueOf(d) != null 
// always true, a double is never an empty string.
String.valueOf(d).trim().length() != 0; 

// same as
int feetPart = (int) (d / 2.54 / 12);
int inchesPart = ((int) (d / 2.54)) % 12;

// same as
return feetPart + "' " + inchesPart + "\"";

Upvotes: 1

BrookLeet
BrookLeet

Reputation: 58

all the answer replace your variable type. my way keeps. only use these codes you will find the magic.

double d = 1.0d;
String s = String.format("%1$.0f", d);
System.out.println(s);

Upvotes: 0

xlecoustillier
xlecoustillier

Reputation: 16351

As you want to store ints in feetPart and inchesPart variables, just declare them as ints :

int feetPart = 0;
int inchesPart = 0;

Then you'll avoid them being displayed as doubles (i.e. with the trailing .0).

Upvotes: 5

Aeronth
Aeronth

Reputation: 814

You can simply cast it into an int.

(int) d;

Upvotes: 3

sameday
sameday

Reputation: 321

You can cast the double variables to an int

return (String.valueOf((int)feetPart)) + "' " + 
String.valueOf((int)inchesPart) + "''";

That should fix it as well.

Upvotes: 1

Related Questions