Java: Convert floating point decimal number to the power of to integer - java

So I have the following number
3.454545E5
Notice the "E" letter which indicates to the power of
Is there a way to conver this number to
3454545
?

double d = 3.454545E5;
int i = (int) d;
Output: 345454.
If you want exactly 3454545:
int i = (int) (d*10);

You can use DecimalFormat to format the number any way you want.
If it is a string, first parse it as a double.

double yourNumber = 3.454545E5;
String output = String.format("%d", yourNumber);

try this
long l = (long) 3.454545E5;

Not sure if I understand you correctly but looks like you're interested in extracting mantissa from the number and dropping the exponent
This should work for you:
double number = 3.454545E5;
int exponent = (int)Math.log10(Math.abs(number)); // exponent = 5
double mantissa = number / Math.pow(10, exponent); // mantisa = 3.454545
To get your number you can multiply mantissa, in your particular example:
int result = (int)(mantissa * 1000000)
//result = 3454545

Can you try doing this?
double num = 3.454545E5;
int num1 = (int)num;
System.out.println(num1);
Here is the result -
345454

Related

How can I get only the decimal value of a number and I will store that value into another variable using Java? [duplicate]

I have a double variable d = 1.15.
I want the number after the decimal point, i.e. "15".
What is best way to achieve this in Java?
I have tried like this:
Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));
But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.
Try this:
String numberD = String.valueOf(d);
numberD = numberD.substring(numberD.indexOf("."));
Now this numberD variable will have value of 15
Try Math.floor();
double d = 4.24;
System.out.println( d - Math.floor( d ));
To prevent rounding errors you could convert them to BigDecimal
double d = 4.24;
BigDecimal bd = new BigDecimal( d - Math.floor( d ));
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.toString() );
Prints 0.2400
Note that the 4 in setScale is the number of digits after the decimal separator ('.')
To have the remainder as an integer value you could modify this to
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
Prints 24
The number after the decimal point is not a well defined concept. For example for "4.24", it could be "0.24", "0.239999999999" (or similar), "24" or "239999999999".
You need to be clear if you are talking about a number or a string of decimal digits ... and whether the input value is a representation of a binary floating point number (in which case "4.24" is most likely an approximation) a decimal floating point number.
Depending on your interpretation, the correct answer will be different.
But i didn't get the proper answer because when I converted d.toString() the answer is 14.999999999999986.
You are running up against the problem that double and float are base-2 floating point formats, and in most cases they CANNOT represent decimal floating point numbers precisely. There is no fix for this ... apart from using something like BigDecimal to represent your numbers. (And even then, some loss of precision is possible whenever you do a division or modulo operation.)
Try out RegEx, here ^\d*\., will search for digits followed by dot and replace with blank.
for(double d : new double[]{1.15,0.009,222.9,3.67434}){
System.out.println(String.valueOf(d).replaceAll("^\\d*\\.",""));
}
gives:
15
009
9
67434
If you want the decimal places and you want to round the result.
double d = 4.24;
System.out.printf("%0.2f%n", d - (long) d);
prints
0.24
If you want a rounded value, you have to determine what precision you want.
double d = 4.24;
double fract = d - (long) d;
fract = (long) (fract * 1e9 + 0.5) / 1e9; // round to the 9 decimal places.
If your double is:
d = 1.25;
And if you do this:
String number = String.valueOf(d);
number = number.substring(number.indexOf(".")).substring(1);
then number will be 25.
I don't know if this is the best way to do this, but it works.
Have you tried d = d%1.0? That should return the remainder of dividing d by 1, which should just be the decimal portion.
You could also do this to get the value as an int: d = (int)((d%1.0)*100)
Instead of d.toString(), try this:
String str = String.format("%.2f", d);
Just as in any other language: multiply by 10 and check the int part of remnant when dividing by 10. The same way you would extract digits from an integer.
short[] digits = new short[max_len];
double tmp = d - ((int) d);
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digit[i] = (short) tmp;
tmp -= (int) tmp;
}
But be aware that for double you need to introduce a precision limit - the maximum number of digits to extract (max_len from the code sample above).
Slight update (added rounding at the edge of precision):
double d = 1.15;
short[] digits = new short[10];
double tmp = d - ((int) d) + 0.5 * 1e-10;
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digits[i] = (short) tmp;
tmp -= (int) tmp;
}
double d = 4.24;
d = (d - Math.floor( d ));
int e = (int)(Math.round(d*100));
System.out.println(e);
Yields 24
Scanner scr= new Scanner (System.in);
double d= scr.nextDouble();
BigDecimal bc= new BigDecimal ((d - Math.floor(d))*1e5);
bc=bc.setScale(4,RoundingMode.HALF_DOWN);
double f = bc.doubleValue();
while(f%10==0)
{
f=f/10;
}
System.out.println(f);
try this :
double d = 1.1512;
int i = (int) (d*100 - Math.floor(d)*100);
now this will give you : 15
ExAMPLE :
Double d = 469.951479;
String string = d.toString();
char[] len = string.substring(string.indexOf(".")).toCharArray();
System.out.println(len);
double myNumber = 1.15;
//numbers After Dot
double n = 2;
double right_of_dot = (myNumber - (int) myNumber)*Math.pow(10,n);
Try this:
var decimalsOnly = (parseFloat(decNum)-parseInt(decNum,10)).toFoxed(2);

How to split a double number by dot into two decimal numbers in Java?

Trying to split a double number into two decimal parts by dot. Like this: 1.9 into 1 and 9; 0.16 into 0 and 16;
Here's what I do, but seems a little redundant, what's the best way to do this?
The origin number will always be like Just 0.x or 1.x or 0.xx or 1.xx and xx > 10
double d = 1.9;
int a, b;
String dString = Double.toString(d);
String aString = dString.substring(0, 1);
String bString = dString.substring(2);
a = Integer.parseInt(aString);
b = Integer.parseInt(bString);
My way of doing this seems using to much String conversion,which I don't think is very efficient.
You can try this way too
double val=1.9;
String[] arr=String.valueOf(val).split("\\.");
int[] intArr=new int[2];
intArr[0]=Integer.parseInt(arr[0]); // 1
intArr[1]=Integer.parseInt(arr[1]); // 9
You could treat the double like a string, and split it on the decimal place.
double d = 13454.92345;
String bob = Double.toString(d);
String[] convert = bob.split("\\.");
int a = Integer.parseInt(convert[0]);
int b = Integer.parseInt(convert[1]);
System.out.println(a); // 13454
System.out.println(b); // 92345
To get the decimal part as an int is not really following any standards, so you are stuck with your special solution for that. Getting the value before the decimal point can be simplified to a simple cast though:
double d = 1.9;
int a, b;
String dString = Double.toString(d);
String bString = dString.substring(2);
a = (int) d;
b = Integer.parseInt(bString);
Note that the substring() and parseInt() fails if the number is 10 or bigger though. You might want to change the substring() call to something like:
String bString = dString.split("\\.")[1];
double num=12.5;
String str=Double.toString(num);
String strarray[]=str.split("\\.");
Now strarray[0] will be holding 12, and strarray[1] will be having 5.You can convert them into integers by writing following code:
int num1=Integer.parseInt(strarray[0]);
int num2=Integer.parseInt(strarray[1]);
double d = 1.9;
String str = Double.toString(d);
String strArray[] = str.split("\\.");
int a = Integer.parseInt(strArray[0]);
int b = Integer.parseInt(strArray[1]);
System.out.print(a + " - " + b);
Try this. This will work.
Here's a two line version:
int a = (int)d;
int b = Integer.parseInt((d + "").split("\\.", 2)[1]).replaceAll("^$", "0"));
The first part is easy - just cast to int, which automatically chops off any decimal part of the number.
The second part is easiest with a Strimg approach - split the string version on a dot and use the second part. Note the addition of "" which generates a string, and the handling of the edge case of there being no decimal part, where 3 as a double prints as 3. - if the result is a blank (guaranteed by the second parameter to split) which is then converted to a zero.
This solution should work for almost any length of the fractional part and doesn't use strings.
For example the accepted answer doesn't work for 0.16
double d = 123.456
long a = (long) d;
double f = d - a;
while (Math.abs((long) f - f) > 0.000001) f *= 10;
long b = (long) f;
// a = 123
// b = 345
Here is another approach:
double d=1.9;
int a;
int b;
a = (int) d/10;
b = (int) d%10;
System.out.print("a");
System.out.print("b");
double dub=1234.5678987;//Variable to be manipulated
long lon=0; //To store before decimal point.
short sh=0;//To store after decimal point.
int deci=10000; //to 4 decimal places
lon=(int)dub;// get the integer part of the number stored in long
sh=(short)((dub-(double)lon)*deci);//deci to required decimal places.
System.out.println(""+lon+"."+sh);
I tried a split on "." and then just parse the string for integers.
String a="";
double x = 2.4;
a=x+"";
String [] v =a.split("\\.");
int before = Integer.parseInt(v[0]);
int after = Integer.parseInt(v[1]);

How to add decimal point before x digits in Java

Lets suppose I have a value 12345678 and a number say x=2, and I want the final output as 123456.78 and if the value of x is 4, the final output would be 1234.5678.
Please tell how would I can achieve this?
Given that you're dealing with shifting a decimal point, I'd probably use BigDecimal:
long integral = 12345678L;
int x = 4; // Or 2, or whatever
BigDecimal unscaled = new BigDecimal(integral);
BigDecimal scaled = unscaled.scaleByPowerOfTen(-x);
System.out.println(scaled); // 1234.5678
BigInteger d = new BigInteger("12345");
BigDecimal one = new BigDecimal(d, 3);//12.345
BigDecimal two = new BigDecimal(d, 2);//123.45
Try this out :
String data = "12345678";
StringBuilder builder = new StringBuilder(data);
int x = 4;
builder.insert(builder.length() - x, ".");
System.out.println(builder);
Divide the value by 10 raise to the power x.

Java Double/Integer

int a = 1;
int b = 10;
int c = 3;
int d = (1/10)*3
System.out.println(d)
Result: 0
How do i make this Calculation work ?
and round up or down ?
It should be:
(1/10)*3 = 0.1 * 3 = 0.3 = 0 and
(4/10)*3 = 0.4 * 3 = 1.2 = 1
Thanks a lot!
1 / 10
This is integer division and as integer division the result is 0.
Then 0 * 3 = 0
You can use double literals:
1.0 / 10.0
Try:
int d = (int) (((double)4/10)*3);
1/10
This line return 0.so 0*3=0.Use double instead of int
as both a and b are integer so the output will also be int which makes 1/10 as 0 and then 0*3=0
You will want to perform the calculation using floating-point representation. Then you can cast the result back to an integer.
I note that you refer in your question to rounding up/down.
Math.round() will help you here.
Returns the closest long to the argument. The result is rounded to an
integer by adding 1/2, taking the floor of the result, and casting the
result to type long.
This will works
int a = 1;
int b = 10;
int c = 3;
int d = (1*3/10);
System.out.println(d);

How do I get the part after the decimal point in Java?

I have a double variable d = 1.15.
I want the number after the decimal point, i.e. "15".
What is best way to achieve this in Java?
I have tried like this:
Double d = 1.15;
String str = d.toString();
int len = str.substring(str.indexOf(".")).length() - 1;
int i= (int) (d * (long)Math.pow(10,len) % (long)Math.pow(10,len));
But I didn't get the proper answer because when I convert d.toString() the answer is 14.999999999999986.
Try this:
String numberD = String.valueOf(d);
numberD = numberD.substring(numberD.indexOf("."));
Now this numberD variable will have value of 15
Try Math.floor();
double d = 4.24;
System.out.println( d - Math.floor( d ));
To prevent rounding errors you could convert them to BigDecimal
double d = 4.24;
BigDecimal bd = new BigDecimal( d - Math.floor( d ));
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.toString() );
Prints 0.2400
Note that the 4 in setScale is the number of digits after the decimal separator ('.')
To have the remainder as an integer value you could modify this to
BigDecimal bd = new BigDecimal(( d - Math.floor( d )) * 100 );
bd = bd.setScale(4,RoundingMode.HALF_DOWN);
System.out.println( bd.intValue() );
Prints 24
The number after the decimal point is not a well defined concept. For example for "4.24", it could be "0.24", "0.239999999999" (or similar), "24" or "239999999999".
You need to be clear if you are talking about a number or a string of decimal digits ... and whether the input value is a representation of a binary floating point number (in which case "4.24" is most likely an approximation) a decimal floating point number.
Depending on your interpretation, the correct answer will be different.
But i didn't get the proper answer because when I converted d.toString() the answer is 14.999999999999986.
You are running up against the problem that double and float are base-2 floating point formats, and in most cases they CANNOT represent decimal floating point numbers precisely. There is no fix for this ... apart from using something like BigDecimal to represent your numbers. (And even then, some loss of precision is possible whenever you do a division or modulo operation.)
Try out RegEx, here ^\d*\., will search for digits followed by dot and replace with blank.
for(double d : new double[]{1.15,0.009,222.9,3.67434}){
System.out.println(String.valueOf(d).replaceAll("^\\d*\\.",""));
}
gives:
15
009
9
67434
If you want the decimal places and you want to round the result.
double d = 4.24;
System.out.printf("%0.2f%n", d - (long) d);
prints
0.24
If you want a rounded value, you have to determine what precision you want.
double d = 4.24;
double fract = d - (long) d;
fract = (long) (fract * 1e9 + 0.5) / 1e9; // round to the 9 decimal places.
If your double is:
d = 1.25;
And if you do this:
String number = String.valueOf(d);
number = number.substring(number.indexOf(".")).substring(1);
then number will be 25.
I don't know if this is the best way to do this, but it works.
Have you tried d = d%1.0? That should return the remainder of dividing d by 1, which should just be the decimal portion.
You could also do this to get the value as an int: d = (int)((d%1.0)*100)
Instead of d.toString(), try this:
String str = String.format("%.2f", d);
Just as in any other language: multiply by 10 and check the int part of remnant when dividing by 10. The same way you would extract digits from an integer.
short[] digits = new short[max_len];
double tmp = d - ((int) d);
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digit[i] = (short) tmp;
tmp -= (int) tmp;
}
But be aware that for double you need to introduce a precision limit - the maximum number of digits to extract (max_len from the code sample above).
Slight update (added rounding at the edge of precision):
double d = 1.15;
short[] digits = new short[10];
double tmp = d - ((int) d) + 0.5 * 1e-10;
for (int i = 0; i < digits.length && tmp != 0; i++)
{
tmp *= 10;
digits[i] = (short) tmp;
tmp -= (int) tmp;
}
double d = 4.24;
d = (d - Math.floor( d ));
int e = (int)(Math.round(d*100));
System.out.println(e);
Yields 24
Scanner scr= new Scanner (System.in);
double d= scr.nextDouble();
BigDecimal bc= new BigDecimal ((d - Math.floor(d))*1e5);
bc=bc.setScale(4,RoundingMode.HALF_DOWN);
double f = bc.doubleValue();
while(f%10==0)
{
f=f/10;
}
System.out.println(f);
try this :
double d = 1.1512;
int i = (int) (d*100 - Math.floor(d)*100);
now this will give you : 15
ExAMPLE :
Double d = 469.951479;
String string = d.toString();
char[] len = string.substring(string.indexOf(".")).toCharArray();
System.out.println(len);
double myNumber = 1.15;
//numbers After Dot
double n = 2;
double right_of_dot = (myNumber - (int) myNumber)*Math.pow(10,n);
Try this:
var decimalsOnly = (parseFloat(decNum)-parseInt(decNum,10)).toFoxed(2);

Categories

Resources