Save value after JAVA comma

Asked

Viewed 302 times

-1

Hello, I need to take a value after the comma to 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?

  • Because the code you’ve already made

  • I don’t understand....

  • Possible duplication: https://answall.com/questions/146438/como-pega-apenas-o-n%C3%Bamero-depois-da-v%C3%Adrgula

  • I came to see this Adriano, but did not understand.

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 method parameter split() requires two bars as the dot is a special character.

  • Good morning André, thanks for the answer, I did not use the code, I used the bottom one that is simpler and can do what I need. Hugs!

2

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

int x = 175%10 //resultado é 5

You don’t even have to divide to work with the decimal. You can already pick it up directly using this technique.

  • I used it and it worked, thank you!!

  • 1

    If the answer served you, mark it as correct. This helps other users who have doubt like yours.

  • I’ve already positive the answer, but it says since I don’t have enough reputation it doesn’t show up here, but it’s computed.

0

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

Declare and initialize the variables you will use:

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

Perform the split operation:

resultado = dividendo/divisor;

Convert the result to a string:

String resultadoString = String.valueOf(resultado);

Now you perform the Split operation (Split String) and store the value of the second part of the split in the resulting String (You need to use the class Pattern and the method 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);
  • Good morning Hugo, thanks! I used the form int x = 175%10 that returns me exactly what I need and the code is simpler, thanks for the help.

  • This way is actually simpler, but it is always good to know that there are several possibilities to solve the same problem! Dispose!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.