How do I get the part after the decimal point in Java? - 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);

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

Change double decimal spaces depending on int value

i want to change the decimal spaces of an double, depending on the int value that i use. I Figured out, that i can change the decimal spaces "manually" by changing to 10 or 1000 and so on, but i dont know how to accomplish this, other than changing said values in the code.
My second quest is how to round double values for example 19.657 up to 19.66, or 19.652 down to 19.65 .
Note :
WITHOUT the use of imports and only the default package
I use Java with Eclipse as my IDE
Thank you in advance for your effort :)
double x = 19.657821456;
int y = 3;
x = x*10;
x = (double)((int) x);
x = x /10;
You can use the DecimalFormat class to format your doubles.
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(10));
>10.00
This will also round values if they exceed the amount of decimals you specified
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(19.657));
>19.66
You can use Decimal Formate to format double value
Example:
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String[] args) {
double input = 3.14159265359;
System.out.println("double : " + input);
System.out.println("double : " + df.format(input)); //3.14
// DecimalFormat, default is RoundingMode.HALF_EVEN
df.setRoundingMode(RoundingMode.DOWN);
System.out.println("\ndouble (RoundingMode.DOWN) : " + df.format(input)); //3.14
df.setRoundingMode(RoundingMode.UP);
System.out.println("double (RoundingMode.UP) : " + df.format(input)); //3.15
}
Output :
double : 3.14159265359
double : 3.14
double (RoundingMode.DOWN) : 3.14
double (RoundingMode.UP) : 3.15
Variable number of digits after decimal. Basically same idea as code in question, just using Math methods, calculating the multiplier as needed (10 or 1000 in question):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = Math.pow(10, digits);
return Math.rint(value * mult) / mult;
}
If not allowed to use Math (standard lib, no import needed), we can calculate the multiplier in a loop and use an offset of 0.5 to round to the nearest integer (negative for negative numbers):
public static double round(double value, int digits) {
if (digits < 0)
throw new IllegalArgumentException("digits must be non-negative: " + digits);
var mult = 1.0;
for (var i = 0; i < digits; i++) {
mult *= 10;
}
var offset = value>0 ? 0.5 : -0.5;
return (int) (value * mult + offset) / mult;
}
Be warned that these methods will only work for small number of digits (intermediate results eventually exceeding the integer or even the double value range)
not tested - please test code before using

how to convert 5.5 to 5.0 in java

I know it may sound stupid. But I don't know how to convert 5.5 into 5.0.
What I have done is:
int expiry = month2 + month1;
int expiry1 = expiry;
int sum = 0;
DecimalFormat df = new DecimalFormat("#.00000");
df.format(expiry);
if (expiry > 12) {
expiry = (expiry / 12);
sum = ((expiry1 - (expiry * 12)) - 1);
System.out.println(sum);
month3 = sum;
year1 = (year1 + expiry);
}
If we consider if condition whenever value of expiry is for example 30, it gives output as 3 because of decimals but i want answer as 2. I tried using Decimal format but does not work. I tried casting but I failed while trying it (maybe I don't know the correct way of doing it).
I tried using pattern
String truncatedValue = String.format("%d", expiry).split("\\.")[0];
and then again converting it into integer but this does not work for me.
As pointed out in the comments, you can use Math.floor.
Another option is to convert to a long or use Math.round. Here's an overview of your options to get x = 5:
// Casting: Discards any decimal places
double a = (long) 5.4;
System.out.println(a); // 5.0
double b = (long) 5.6;
System.out.println(b); // 5.0
double c = (long) -5.4;
System.out.println(c); // -5.0
double d = (long) -5.6;
System.out.println(d); // -5.0
// Math.floor: Rounds towards negative infinity
double e = Math.floor(5.4);
System.out.println(e); // 5.0
double f = Math.floor(5.6);
System.out.println(f); // 5.0
double g = Math.floor(-5.4);
System.out.println(g); // -6.0
double h = Math.floor(-5.6);
System.out.println(h); // -6.0
// Math.round: Rounds towards the closest long
double i = Math.round(5.4);
System.out.println(i); // 5.0
double j = Math.round(5.6);
System.out.println(j); // 6.0
double k = Math.round(-5.4);
System.out.println(k); // -5.0
double l = Math.round(-5.6);
System.out.println(l); // -6.0
If you just want to get rid of the decimal places, casting is just fine.
If you want to round to the next smaller value, Math.floor is your friend.
If you want to round the way most of us learned it in school, Math.round will do.
For future reference, you can assume that basic math operations (like rounding up/down) are implemented in respective libraries, so it doesn't hurt to have a quick search on the topic.

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

Rounding up to 2 decimal place

I have this code below, my desired answer is 37.58 and not 37.56 or 37.60 after inputting 37576
BigDecimal n = new BigDecimal(num);
BigDecimal t = new BigDecimal(100);
BigDecimal res = n.divide(t);
BigDecimal b =res.setScale(1, BigDecimal.ROUND_HALF_UP);
DecimalFormat forma = new DecimalFormat("K0.00");
String bigf = forma.format(b);
txtnewk.setText(" " + bigf);
what changes do I have to make?
With the following code:
String num = "37576";
BigDecimal n = new BigDecimal(num);
BigDecimal t = new BigDecimal(1000);
BigDecimal res = n.divide(t);
BigDecimal b = res.setScale(2, BigDecimal.ROUND_HALF_UP);
b is 37.58 as desired.
Use this code for rounding numbers:
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
You are using wrong version of divide (if you are rounding it immediately). Value of setScale is wrong. You should have:
BigDecimal res = n.divide(t, 2, BigDecimal.ROUND_HALF_UP);
Using double you can do
long l = 37576; // or Long.parseLong(text);
double v = Math.round(l / 10.0) / 100.0;
System.out.println(v);
prints
37.58
The first rounded / 10.0 says you want to drop the lowest digit by rounding and the / 100.0 says you want to shift the decimal place by two digits.

Categories

Resources