Newbie Question

O

Obi Wan Shinobi

Hello there,

I've just started learning Java. What I would like to know is if I
have a variable of type double or float, how can I extract the
fractional portion of that number and place it into a short or int
variable?

Many thanks in advance.
 
R

Roedy Green

I've just started learning Java. What I would like to know is if I
have a variable of type double or float, how can I extract the
fractional portion of that number and place it into a short or int
variable?

see http://mindprod.com/jgloss/round.html
for how to extract the integer part. then subtract.

Multiply it first if you really mean you want an int result. There is
also floatToIntBits.
 
J

Jim Sculley

Obi said:
Hello there,

I've just started learning Java. What I would like to know is if I
have a variable of type double or float, how can I extract the
fractional portion of that number and place it into a short or int
variable?

Uhm, you can't. Short and int only accept integers, and the fractional
part of a double or float is, of course, not an integer.

Unless you mean that you wish to take a number such as 1.25, and store
'25'. In that case, String.valueOf(), Short.parseShort() and
Integer.parseInt() may be of assistance.

Jim S.
 
O

Oscar kind

Obi Wan Shinobi said:
I've just started learning Java. What I would like to know is if I
have a variable of type double or float, how can I extract the
fractional portion of that number and place it into a short or int
variable?

You don't, as 0.2 is greater than 0.15, but 2 is smaller than 15.
The best way to do such a thing is to use fixed point numbers.

A code snippet to illustrate:

BigDecimal number = new DigBecimal(3.05);
number = number.setScale(3, BigDecimal.ROUND_HALF_UP);
number = number.substract(BigDecimal.valueOf(number.longValue()));
long fraction = number.unscaledValue().longValue();

The variable fraction now contains 50. This is the fractional part times
1000, because the scale was set to 3 (10^3 = 1000).


kind regards,
Oscar
 
S

Steve R. Burrus

Oscar said:
You don't, as 0.2 is greater than 0.15, but 2 is smaller than 15.
The best way to do such a thing is to use fixed point numbers.

A code snippet to illustrate:

BigDecimal number = new DigBecimal(3.05);

Oscar, you DID mean to write "BigDecimal number = new BigDecimal(3.05);"
right? and not the "BigDecimal number = new DigBecimal(3.05);" that you
mistakenly wrote??!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top