How to add decimal point before x digits in Java - 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.

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);

using BigDecimal for very large numbers

I have this code:
while (counter <= t)
{
a = a * counter;
c = c * r + a;
counter++;
}
and I have t with the value 101835.
The output should be 7.1*10^438, but NetBeans shows
the output as infinity.
Is there anything that will make the output as a decimal number?
Yes, the only thing which you should use here is BigDecimal class. It'll easily handle that complex value without burdening you.
The maximum supported double value is only around 1.7 * 10^ 308 as given by Double.MAX_VALUE specified for Java.
A double as defined by IEEE-754 can't represent such a number, it's too large. The bounds are approximately between -10308 and 10308.
You need to use a BigDecimal to represent it: a number with an arbitrary number of bytes to represent numbers.
Better way to implement this:
double c = 0.0005d;//initialize c
double r = 0.01d; //initialize r
double a = 0.0006d;//initialize a
BigDecimal abd = new BigDecimal(a); //BigDecimal for a
BigDecimal cbd = new BigDecimal(c); //BigDecimal for c
BigDecimal rbd = new BigDecimal(r); //BigDecimal for r
for (int counter = 1; counter <= t; counter++) {//perhaps other offset for counter?
abd = abd.multiply(new BigDecimal(counter));
cbd = cbd.multiply(rbd).add(abd);
}
A potential problem with this approach is that the precision is too high: Java will calculate all operations exactly resulting in numbers that have thousands of digits. Since every operation blows up the number of digits, within a few iterations, simple addition and multiplication operations become unfeasible.
You can solve this by defining a precision using the optional MathContext parameter: it determines on how precise the result should be. You can for instance use MathContext.DECIMAL128:
int t = 101835;
double c = 0.0005d;//initialize c
double r = 0.01d; //initialize r
double a = 0.0006d;//initialize a
BigDecimal abd = new BigDecimal(a); //BigDecimal for a
BigDecimal cbd = new BigDecimal(c); //BigDecimal for c
BigDecimal rbd = new BigDecimal(r); //BigDecimal for r
for (int counter = 1; counter <= t; counter++) {//perhaps other offset for counter?
abd = abd.multiply(new BigDecimal(counter),MathContext.DECIMAL128);
cbd = cbd.multiply(rbd,MathContext.DECIMAL128).add(abd,MathContext.DECIMAL128);
}
System.out.println(abd);
System.out.println(cbd);
This gives:
abd = 3.166049846031012773846494375835059E+465752
cbd = 3.166050156931013454758413539958330E+465752
This is approximately correct, after all the result of a should be:
Which is approximately correct according to Wolfram Alpha.
Furthermore I would advice to use a for and not a while if it is a for loop. Since while tends to create another type of infinity: an infinite loop ;).

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]);

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

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

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