how to only get the decimal of a number

801 views java
2

the assignment that I am working on requires that you take the floating point of a number. For example, if I had 4.233, it would only give me (.233). How would I be able to do this? I tried to use the % operator; however, it does not give the exact results.

Thank You

answered question

How would you do it not in Java? Like, just you as a human -- how would you do it? Once you figure that out, try to break it down into individual steps that are small enough that you can either do them yourself, or ask more directed questions.

Split on "." and then pop the first element out

What do you mean % does not give "the exact results"? Something like number % 1.0 should work as expected.

3 Answers

8

There are basically two ways. Numerically, you can subtract the int value of the initial double value to get the part that is floating point. Or, you can convert to a String and split on the decimal point. Like,

double d = 4.233;
double fp = d - (int)d;
System.out.printf("%f%n", fp);
System.out.printf(".%s%n", String.valueOf(d).split("\\.")[1]);

I get

0.233000
.233

respectively.

posted this
9

you can try this:

float f = 23.33;
float f1 = f - (int)f; //f1 = 0.33
float f2 = f - Math.floor(f); //f2 = 0.33

posted this
8

Thanks Everyone. I relize my mistake; and quite frankly its pretty funny haha. I hope this lightened someone's day; and yes, this was a real question that got me for over an hour :[

posted this

Have an answer?

JD

Please login first before posting an answer.