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.
Integer part gets from simple casting and for fractional - string splitting:
double value = 123.004567890
int integerPart = (int) value; // 123
int fractionPart =
Integer.valueOf(String.valueOf(value)
.split(".")[1]); // 004567890
/**
* To control zeroes omitted from start after parsing.
*/
int decimals =
String.valueOf(value)
.split(".")[1].length(); // 9
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:
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);
}
}
[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.
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
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);
}
}
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
Since this 1-year old question was kicked up by someone who corrected the question subject, and this question is been tagged with jsp, and nobody here was able to give a JSP targeted answer, here is my JSP-targeted contribution.
Use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib
) 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 SSCCE, just copy'n'paste'n'run it.
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
// Just for quick prototyping. Don't do this in real! Use servlet/javabean.
double d = 3.25;
request.setAttribute("d", d);
%>
<!doctype html>
<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>
Output:
Whole: 3
Fraction: .25
That's it. No need to massage it with help of raw Java code.
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;
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>
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);
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);
}
}
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();
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
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.
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);
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;
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();
[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.
double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;
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
Integer part gets from simple casting and for fractional - string splitting:
double value = 123.004567890
int integerPart = (int) value; // 123
int fractionPart =
Integer.valueOf(String.valueOf(value)
.split(".")[1]); // 004567890
/**
* To control zeroes omitted from start after parsing.
*/
int decimals =
String.valueOf(value)
.split(".")[1].length(); // 9
// 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
Don't know if this is faster but I'm using
float fp = ip % 1.0f;
Since this 1-year old question was kicked up by someone who corrected the question subject, and this question is been tagged with jsp, and nobody here was able to give a JSP targeted answer, here is my JSP-targeted contribution.
Use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib
) 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 SSCCE, just copy'n'paste'n'run it.
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
// Just for quick prototyping. Don't do this in real! Use servlet/javabean.
double d = 3.25;
request.setAttribute("d", d);
%>
<!doctype html>
<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>
Output:
Whole: 3
Fraction: .25
That's it. No need to massage it with help of raw Java code.
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);
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;
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>
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
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);
[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.
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);
Don't know if this is faster but I'm using
float fp = ip % 1.0f;
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.
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);
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);
}
}
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.
[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.
// 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
Source: Stackoverflow.com