How to separate a number in two

2

How could I separate a number with decimals into two other numbers? The idea is: when entering a number in the terminal, for example 125,69, when passing the number to the code pull the first two houses (decimals 69) to one variable, and the real number (125) to another variable.

package eng_software;
import java.util.Scanner;

public class alg {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    double valorEntrada = sc.nextDouble();
  }
}

I need to know the type of command to split the number and send it to other variables.

    
asked by anonymous 20.03.2018 / 23:25

3 answers

8
double real = Math.floor(valorEntrada);
double frac = valorEntrada % 1;
    
20.03.2018 / 23:44
1

This specific case can be worked with strings. I do not really like the floating-point alternative so much to make a response because of the floating point problem .

So, how to solve the problem? Well, reading a string. And working with string. And if holding only in string.

Considering that the return is an object of class PartesNumero with the fields String parteInteira and String parteDecimal , we could do the following constructor:

public PartesNumero(String numeroCompleto) {
  String partes[] = numeroCompleto.split("[^0-9]");

  if ("".equals(partes[0]) {
    this.parteInteira = 0; // fallback para entradas como ".75"
  } else {
    this.parteInteira = partes[0];
  }
  if (partes.length > 1) {
    this.parteDecimal = partes[1];
  } else {
    this.parteDecimal = "";
  }
}

And to read a string from the entry (not doing any type validation in the meantime):

Scanner sc = new Scanner(System.in);
String entrada = sc.next();

The complete program would then be:

public class Main {
  public class PartesNumero {
    public final String parteInteira;
    public final String parteDecimal;

    public PartesNumero(String numeroCompleto) {
      String partes[] = numeroCompleto.split("[^0-9]");

      if ("".equals(partes[0]) {
        this.parteInteira = 0; // fallback para entradas como ".75"
      } else {
        this.parteInteira = partes[0];
      }
      if (partes.length > 1) {
        this.parteDecimal = partes[1];
      } else {
        this.parteDecimal = "";
      }
    }
  }

  public static void main(String []args) {
    Scanner sc = new Scanner(System.in);
    String entrada = sc.next();
    PartesNumero partes = new PartesNumero(entrada);
    System.out.println(partes.parteInteira);
    System.out.println(partes.parteDecimal);
  }
}
    
21.03.2018 / 17:20
0
 double x = 125.69;
    double decimal = x % 1;
    double inteiro = x - decimal;
    System.out.println("Decimal: "+decimal);
    System.out.println("Inteiro: "+inteiro);
    
21.03.2018 / 02:15