You can multiply the value by 10^n
, in which n
is the number of decimal places you want to show. Then simply subtract from that value the entire part, which is ((int) x) * 10^n
.
In your case, with n = 2
and x = 102.33
, x*10^n = 10233.00
and ((int) x)*10^n = 10200.00
. After making the subtraction x*10^n - ((int) x)*10^n
, you will have 33.00
as value and just convert to whole.
So your code would look that way:
public void printDecimal(double x, int n){
double p = Math.pow(10.0, n);
int dec = (int) (x*p - ((int) x)*p);
System.out.println(dec);
}
or if you want to return the value:
public int decimal(double x, int n){
double p = Math.pow(10.0, n);
return (int) (x*p - ((int) x)*p);
}
If you want the value in the format 0.33
, just divide by 10^n
. Note that you could simply not multiply by 10^n
, but it would have accuracy problems and the output to 102.33
would be something like 0.3299999999999983
. To avoid this problem, we can multiply by 10^n
, perform operations with integer values and then split by 10^n
.
public static void printDecimal(double x, int n){
double p = Math.pow(10.0, n);
int dec = (int) (x*p - ((int) x)*p);
System.out.println(dec/p);
}
Is there somewhere I can study Regex?
– andrecatete
It has some legal guides like this one from https://medium.com/trainingcenter/understandingde-uma-vez-por-todas-expressions-regulares-parte-1-introduction-dfe63e289dc3 and sites like https://www.debuggex.com that draw the diagram of your regex where you write @andrecatete
– Joaquim Cavalcanti