Save value after the comma JAVA

-1
Hello, I need to get a value after the comma to from it do some operations, for example, 175/10 = 17.5, I need to save this value .5 as 5. My number will always be divided by 10, can you help me please?

    
asked by anonymous 12.12.2018 / 19:47

3 answers

2

You can turn it into String and break it to get the value, like this:

double f = 175.0 / 10.0; // f tem o valor 17.5
String s = String.valueOf(f); // converter para String

String s1 = s.split("\.")[1]; //quebrar aonde esta o ponto e pegar o valor após

double x  = Double.valueOf(s1); //converter de volta para double

Note that the parameter of the split() method requires both bars because the point is a special character.

    
12.12.2018 / 20:08
2

Use the module operator, which returns you the rest of a division, which is the value you want:

int x = 175%10 //resultado é 5

You do not even need to split and then work with the decimal. You can already get it directly using this technique.

    
12.12.2018 / 20:24
0

Using the conversion to String, you can do this as follows.

Declare and initialize the variables you will use:

double divisor = 10;
double dividendo = 175;
double resultado = 0;
int casaDecimal = 0;

Perform split operation:

resultado = dividendo/divisor;

Convert the result to a string:

String resultadoString = String.valueOf(resultado);

Now you perform the Split operation and store the value of the second split part in the String resultString (You need to use the Pattern class and the quote , because "." is recognized as a regex ):

resultadoString = resultadoString.split(Pattern.quote("."))[1];

Now just convert the String to integer (in the example) or double, as you wish:

cadaDecimal = Integer.valueOf(resultadoString);
    
12.12.2018 / 20:27