How do I get whole and fractional parts from double in JSP/Java?
Asked Answered
C

18

114

How do I get whole and fractional parts from double in JSP/Java ? If the value is 3.25 then I want to get fractional =.25, whole = 3

How can we do this in Java?

Cyme answered 5/12, 2008 at 11:38 Comment(2)
You seem to have an inaccurate idea of what mantissa and exponent are. They aren't just "whole part" and "fractional part". See en.wikipedia.org/wiki/Floating_pointWinebibber
Keep the original title otherwise most of the answers don't make sense.Soelch
E
105

http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm

double num;
long iPart;
double fPart;

// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);

Outputs:

Integer part = 2
Fractional part = 0.2999999999999998
Elkeelkhound answered 5/12, 2008 at 12:15 Comment(7)
Actually this page is the first hit on a google search for "get fractional and whole part out from double java" =)Scolopendrid
Actually this answer is incorrect, for values larger than long can represent it will give huge numbers in the fractional part. Dan Vinton answer below is just as simple and always returns the correct result.Hazelton
so actually, this is not correct, as you can see in the output. the input is fraction of 3 and output is 29999999...using BigDecimal instead of Double will do the trick thoughAdna
0.2999999999999 is equal to 0.3Shabbir
@Adna No, the input is a number which is very close to 2.3, but surely not 2.3. And there's nothing wrong with the output, unless you want much more than 10 valid digits. All you need is some rounding in each output (e.g., format %.9f) which is usually less pain than BigDecimal. The only problem here is the overflow.Reputable
Converting double to int is almost always a bad idea. Because e.g. for (long)1.0e100 you will get 0. A lot of the times you need the double value simply "floored" for which there is floor(). If you want both integral and fraction parts use modf(). Really, this is a bad answer.Ula
@Ula there is no modf() in JavaFacilitation
T
171
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
Threw answered 5/12, 2008 at 11:50 Comment(5)
Why is this downvoted? Works fine, and with my edit will work with negative values as well.Chafin
The integer part could be => long longPart = (long)3.25Eradis
Won't work for neg. values. I.e. -3.25 % 1 = 0.75 not 0.25. So integralPart will be -3.25 - 0.75 = -4.Vodka
@WindRider, I checked for negative.. and its works.. however for decimal places which are small in number, there will be a slight error. Ex. for -03.0025 it returns -0.0024999999999999467 and -3.0Reheat
The confusion here is because some languages, such as Python, use % to mean modulo (-3.25 % 1 == 0.75) and others, such as Java, Fortran, C, and C++, use % to mean remainder (-3.25 % 1 == -0.25). WindRider may have typed it into a Python REPL for expediency, but that answer is misleading because this question is about the JVM.Babita
E
105

http://www.java2s.com/Code/Java/Data-Type/Obtainingtheintegerandfractionalparts.htm

double num;
long iPart;
double fPart;

// Get user input
num = 2.3d;
iPart = (long) num;
fPart = num - iPart;
System.out.println("Integer part = " + iPart);
System.out.println("Fractional part = " + fPart);

Outputs:

Integer part = 2
Fractional part = 0.2999999999999998
Elkeelkhound answered 5/12, 2008 at 12:15 Comment(7)
Actually this page is the first hit on a google search for "get fractional and whole part out from double java" =)Scolopendrid
Actually this answer is incorrect, for values larger than long can represent it will give huge numbers in the fractional part. Dan Vinton answer below is just as simple and always returns the correct result.Hazelton
so actually, this is not correct, as you can see in the output. the input is fraction of 3 and output is 29999999...using BigDecimal instead of Double will do the trick thoughAdna
0.2999999999999 is equal to 0.3Shabbir
@Adna No, the input is a number which is very close to 2.3, but surely not 2.3. And there's nothing wrong with the output, unless you want much more than 10 valid digits. All you need is some rounding in each output (e.g., format %.9f) which is usually less pain than BigDecimal. The only problem here is the overflow.Reputable
Converting double to int is almost always a bad idea. Because e.g. for (long)1.0e100 you will get 0. A lot of the times you need the double value simply "floored" for which there is floor(). If you want both integral and fraction parts use modf(). Really, this is a bad answer.Ula
@Ula there is no modf() in JavaFacilitation
S
25

Use JSTL (installation instructions here) fmt taglib. There's a <fmt:formatNumber> tag which does exactly what you want and in a quite easy manner with help of maxFractionDigits and maxIntegerDigits attributes.

Here's an MCVE, just copy'n'paste'n'run it.

<!DOCTYPE html>
<%@ taglib uri="jakarta.tags.fmt" prefix="fmt" %>
<%
    // Just for quick prototyping. Don't do this in real! Use servlet/javabean.
    double d = 3.25;
    request.setAttribute("d", d);
%>
<html lang="en">
    <head>
        <title>SO question 343584</title>
    </head>
    <body>
        <p>Whole: <fmt:formatNumber value="${d}" maxFractionDigits="0" />
        <p>Fraction: <fmt:formatNumber value="${d}" maxIntegerDigits="0" />
    </body>
</html>

(NOTE: if you're not on JSTL 3.0+ yet, use uri="http://java.sun.com/jsp/jstl/fmt" instead)

Output:

Whole: 3

Fraction: .25

That's it. No need to massage it with help of plain Java code.

Selfcongratulation answered 13/2, 2010 at 13:20 Comment(0)
F
8

The original question asked for the exponent and mantissa, rather than the fractional and whole part.

To get the exponent and mantissa from a double you can convert it into the IEEE 754 representation and extract the bits like this:

long bits = Double.doubleToLongBits(3.25);

boolean isNegative = (bits & 0x8000000000000000L) != 0; 
long exponent      = (bits & 0x7ff0000000000000L) >> 52;
long mantissa      =  bits & 0x000fffffffffffffL;
Fearnought answered 5/12, 2008 at 11:44 Comment(4)
Isn't the first bit of the mantinssa implicitly set to 1, so the mantissa should be (bits & 0x000fffffffffffffL) | 0x0010000000000000L?Lieabed
Rasmus it wasnt a ryt output Output: exponent 0 and mantissa 2814749767106560 and if u choose urs agnul the mantissa is 0Cyme
Broken with 4 up votes:) Although I see what the code is trying to do with taking apart double value at its joints, the code doesn't seem to output the right values.Elkeelkhound
@agnul: I think "mantissa" usually refers to just the value of the bits. You might just convert this to the significand by (sometimes) prepending a 1 bit. But according to Wikipedia, the word mantissa is now deprecated in favor of "fraction".Fearnought
S
5

The mantissa and exponent of an IEEE double floating point number are the values such that

value = sign * (1 + mantissa) * pow(2, exponent)

if the mantissa is of the form 0.101010101_base 2 (ie its most sigificant bit is shifted to be after the binary point) and the exponent is adjusted for bias.

Since 1.6, java.lang.Math also provides a direct method to get the unbiased exponent (called getExponent(double))

However, the numbers you're asking for are the integral and fractional parts of the number, which can be obtained using

integral = Math.floor(x)
fractional = x - Math.floor(x)

though you may you want to treat negative numbers differently (floor(-3.5) == -4.0), depending why you want the two parts.

I'd strongly suggest that you don't call these mantissa and exponent.

Soelch answered 5/12, 2008 at 12:5 Comment(0)
C
5

Don't know if this is faster but I'm using

float fp = ip % 1.0f;
Carboy answered 9/10, 2013 at 23:7 Comment(0)
W
4

Main logic you have to first find how many digits are there after the decimal point.
This code works for any number upto 16 digits. If you use BigDecimal you can run it just for upto 18 digits. put the input value (your number) to the variable "num", here as an example i have hard coded it.

double num, temp=0;
double frac,j=1;

num=1034.235;
// FOR THE FRACTION PART
do{
j=j*10;
temp= num*j;
}while((temp%10)!=0);       

j=j/10;
temp=(int)num;
frac=(num*j)-(temp*j);

System.out.println("Double number= "+num);      
System.out.println("Whole part= "+(int)num+" fraction part= "+(int)frac);
Willy answered 29/8, 2013 at 17:38 Comment(3)
Now the person that did the down-vote (not me btw), should have explained why there was a down-vote. That's not good. But all of us had a score of 1 at some point or other.Mozza
@Mozza the question was to separate 3.25 as '3' and '25', and the accepted answer will never ever give '25', it will always give '2599999999'Willy
This anwer is very useful if you want the fractional part as an integerParlando
M
3

[Edit: The question originally asked how to get the mantissa and exponent.]

Where n is the number to get the real mantissa/exponent:

exponent = int(log(n))
mantissa = n / 10^exponent

Or, to get the answer you were looking for:

exponent = int(n)
mantissa = n - exponent

These are not Java exactly but should be easy to convert.

Maggi answered 5/12, 2008 at 12:1 Comment(0)
D
1

What if your number is 2.39999999999999. I suppose you want to get the exact decimal value. Then use BigDecimal:

Integer x,y,intPart;
BigDecimal bd,bdInt,bdDec;
bd = new BigDecimal("2.39999999999999");
intPart = bd.intValue();
bdInt = new BigDecimal(intPart);
bdDec = bd.subtract(bdInt);
System.out.println("Number : " + bd);
System.out.println("Whole number part : " + bdInt);
System.out.println("Decimal number part : " + bdDec);
Dehorn answered 22/10, 2016 at 3:47 Comment(0)
L
0

Since the fmt:formatNumber tag doesn't always yield the correct result, here is another JSP-only approach: It just formats the number as string and does the rest of the computation on the string, since that is easier and doesn't involve further floating point arithmetics.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<%
  double[] numbers = { 0.0, 3.25, 3.75, 3.5, 2.5, -1.5, -2.5 };
  pageContext.setAttribute("numbers", numbers);
%>

<html>
  <body>
    <ul>
      <c:forEach var="n" items="${numbers}">
        <li>${n} = ${fn:substringBefore(n, ".")} + ${n - fn:substringBefore(n, ".")}</li>
      </c:forEach>
    </ul>
  </body>
</html>
Lobel answered 10/3, 2010 at 11:43 Comment(1)
Just try all the numbers from my example. fmt:formatNumber rounds its argument, which is not wanted in this case.Lobel
T
0

A lot of these answers have horrid rounding errors because they're casting numbers from one type to another. How about:

double x=123.456;
double fractionalPart = x-Math.floor(x);
double wholePart = Math.floor(x);
Tram answered 5/9, 2014 at 4:12 Comment(0)
A
0

The accepted answer don't work well for negative numbers between -0 and -1.0 Also give the fractional part negative.

For example: For number -0,35

returns

Integer part = 0 Fractional part = -0.35

If wou are working with GPS coordinates it is better to have a result with the signum on the integer part as:

Integer part = -0 Fractional part = 0.35

Theses numbers are used for example for GPS coordinates, where are important the signum for Lat or Long position

Propose code:

    double num;
    double iPart;
    double fPart;

    // Get user input
    num = -0.35d;
    iPart = (long) num;
    //Correct numbers between -0.0 and -1.0
    iPart = (num<=-0.0000001 && num>-1.0)? -iPart : iPart ;
    fPart = Math.abs(num - iPart);
    System.out.println(String.format("Integer part = %01.0f",iPart));
    System.out.println(String.format("Fractional part = %01.04f",fPart));

Output:

Integer part = -0
Fractional part = 0,3500
Adornment answered 7/8, 2015 at 12:6 Comment(0)
S
0

Since Java 8, you can use Math.floorDiv.

It returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient.

Some examples:

floorDiv(4, 3) == 1
floorDiv(-4, 3) == -2

Alternatively, the / operator can be used:

(4 / 3) == 1
(-4 / 3) == -1

References:

Squashy answered 27/10, 2015 at 5:37 Comment(0)
I
0

I would use BigDecimal for the solution. Like this:

    double value = 3.25;
    BigDecimal wholeValue = BigDecimal.valueOf(value).setScale(0, BigDecimal.ROUND_DOWN);
    double fractionalValue = value - wholeValue.doubleValue();
Inadvertent answered 22/12, 2015 at 12:21 Comment(0)
M
0
String value = "3.06";

if(!value.isEmpty()){
    if(value.contains(".")){    
        String block = value.substring(0,value.indexOf("."));
        System.out.println(block);
    }else{
        System.out.println(value);
    }
}
Mullite answered 4/9, 2016 at 8:54 Comment(1)
This answer has been flagged as low quality. If it answers the question, consider adding a bit of text to explain how it works.Diskson
H
0
// target float point number
double d = 3.025;

// transfer the number to string
DecimalFormat df = new DecimalFormat();
df.setDecimalSeparatorAlwaysShown(false);
String format = df.format(d);

// split the number into two fragments
int dotIndex = format.indexOf(".");
int iPart = Integer.parseInt(format.substring(0, dotIndex)); // output: 3
double fPart = Double.parseDouble(format.substring(dotIndex)); // output: 0.025
Hwu answered 25/4, 2020 at 10:12 Comment(0)
C
0

OK this is maybe late, but i think the best and more accurate approach is using BigDecimal

double d = 11.38;

BigDecimal bigD = BigDecimal.valueOf(d);
int intPart = bigD.intValue();
double fractionalPart = bigD.subtract(BigDecimal.valueOf(intPart)).doubleValue();

System.out.println(intPart); // 11
System.out.println(fractionalPart ); //0.38
Calumnious answered 19/6, 2020 at 21:11 Comment(5)
If you have a double, it has float imprecision. Converting it to a BigDecimal will not magically restore its precision.Lonne
@Taschi i think the question is about separating the int and the fractional part, not about restore its precision!Calumnious
Omar, you specifically talked about your approach being "more accurate", which I think is just not true. Your answer is entirely acceptable but that wording seems misleading to me, which is why I commented on it.Lonne
@Taschi, i said that because in many answers you lose value when you get the output, e.g. input (5.03) output int = 5 , fractional = 0.0299999 , we are talking about inputs and outputs, u put value and get back your value without losing 0.001% of it! and this accurate, not misleading!Calumnious
yes. You lose precision when you store something as a double in the first place. Rounding when converting to a BigDecimal also loses precision. Those two losses of precision may cancel each other out, but that does not "restore" precision, because restoring precision is mathematically impossible. You cannot pull information out of thin air.Lonne
C
-2
public class MyMain2 {
    public static void main(String[] args) {
        double myDub;
        myDub=1234.5678;
        long myLong;
        myLong=(int)myDub;
        myDub=(myDub%1)*10000;
        int myInt=(int)myDub;
        System.out.println(myLong + "\n" + myInt);
    }
}
Cynthla answered 6/4, 2009 at 11:31 Comment(1)
This only works if the number has exactly 4 decimal places. Not otherwise.Faris

© 2022 - 2024 — McMap. All rights reserved.