Inicio » Cursos » Android Básico App Restaurante

Curso Android Básico App Restaurante

Capitulo 13 ➜ Programando la Calculadora en JAVA

Programando la Calculadora en JAVA

¿Cómo programar en JAVA una Calculadora IGV en Android Studio?

Programando la Calculadora en JAVA, crearemos una clase para gestionar la conversión de números a letras, posteriormente implementaremos la lógica IGV

CREANDO LA CLASE LETRAS


import java.util.regex.Pattern;

/**
 *
 * @author CALIDAD
 */
public class Letras {

    private final String[] UNIDADES = {"", "un ", "dos ", "tres ", "cuatro ", "cinco ", "seis ", "siete ", "ocho ", "nueve "};
    private final String[] DECENAS = {"diez ", "once ", "doce ", "trece ", "catorce ", "quince ", "dieciseis ",
            "diecisiete ", "dieciocho ", "diecinueve", "veinte ", "treinta ", "cuarenta ",
            "cincuenta ", "sesenta ", "setenta ", "ochenta ", "noventa "};
    private final String[] CENTENAS = {"", "ciento ", "doscientos ", "trecientos ", "cuatrocientos ", "quinientos ", "seiscientos ",
            "setecientos ", "ochocientos ", "novecientos "};

    public Letras() {
    }

    public String Convertir(String numero, boolean mayusculas) {
        String literal = "";
        String parte_decimal;
        //si el numero utiliza (.) en lugar de (,) -> se reemplaza
        numero = numero.replace(".", ",");
        //si el numero no tiene parte decimal, se le agrega ,00
        if (numero.indexOf(",") == -1) {
            numero = numero + ",00";
        }
        //se valida formato de entrada -> 0,00 y 999 999 999,00
        if (Pattern.matches("\\d{1,9},\\d{1,2}", numero)) {
            //se divide el numero 0000000,00 -> entero y decimal
            String Num[] = numero.split(",");
            //de da formato al numero decimal
            parte_decimal = "y " + Num[1] + "/100 Soles.";
            //se convierte el numero a literal
            if (Integer.parseInt(Num[0]) == 0) {//si el valor es cero
                literal = "cero ";
            } else if (Integer.parseInt(Num[0]) > 999999) {//si es millon
                literal = getMillones(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 999) {//si es miles
                literal = getMiles(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 99) {//si es centena
                literal = getCentenas(Num[0]);
            } else if (Integer.parseInt(Num[0]) > 9) {//si es decena
                literal = getDecenas(Num[0]);
            } else {//sino unidades -> 9
                literal = getUnidades(Num[0]);
            }
            //devuelve el resultado en mayusculas o minusculas
            if (mayusculas) {
                return (literal + parte_decimal).toUpperCase();
            } else {
                return (literal + parte_decimal);
            }
        } else {//error, no se puede convertir
            return literal = null;
        }
    }

    /* funciones para convertir los numeros a literales */
    private String getUnidades(String numero) {// 1 - 9
        //si tuviera algun 0 antes se lo quita -> 09 = 9 o 009=9
        String num = numero.substring(numero.length() - 1);
        return UNIDADES[Integer.parseInt(num)];
    }

    private String getDecenas(String num) {// 99
        int n = Integer.parseInt(num);
        if (n < 10) {//para casos como -> 01 - 09
            return getUnidades(num);
        } else if (n > 19) {//para 20...99
            String u = getUnidades(num);
            if (u.equals("")) { //para 20,30,40,50,60,70,80,90
                return DECENAS[Integer.parseInt(num.substring(0, 1)) + 8];
            } else {
                return DECENAS[Integer.parseInt(num.substring(0, 1)) + 8] + "y " + u;
            }
        } else {//numeros entre 11 y 19
            return DECENAS[n - 10];
        }
    }

    private String getCentenas(String num) {// 999 o 099
        if (Integer.parseInt(num) > 99) {//es centena
            if (Integer.parseInt(num) == 100) {//caso especial
                return " cien ";
            } else {
                return CENTENAS[Integer.parseInt(num.substring(0, 1))] + getDecenas(num.substring(1));
            }
        } else {//por Ej. 099
            //se quita el 0 antes de convertir a decenas
            return getDecenas(Integer.parseInt(num) + "");
        }
    }

    private String getMiles(String numero) {// 999 999
        //obtiene las centenas
        String c = numero.substring(numero.length() - 3);
        //obtiene los miles
        String m = numero.substring(0, numero.length() - 3);
        String n = "";
        //se comprueba que miles tenga valor entero
        if (Integer.parseInt(m) > 0) {
            n = getCentenas(m);
            return n + "mil " + getCentenas(c);
        } else {
            return "" + getCentenas(c);
        }

    }

    private String getMillones(String numero) { //000 000 000
        //se obtiene los miles
        String miles = numero.substring(numero.length() - 6);
        //se obtiene los millones
        String millon = numero.substring(0, numero.length() - 6);
        String n = "";
        if (millon.length() > 1) {
            n = getCentenas(millon) + "millones ";
        } else {
            n = getUnidades(millon) + "millon ";
        }
        return n + getMiles(miles);
    }
}

LA CLASE PRINCIPAL 

public class MainActivity extends AppCompatActivity {


    private EditText subtotal_, igv_;
    private Button btn_;
    private TextView total_, totaltexto_;
    private double valor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        subtotal_ = findViewById(R.id.subtotal);
        igv_ = findViewById(R.id.igv);
        btn_ = findViewById(R.id.btncalcula);
        total_ = findViewById(R.id.total);
        totaltexto_ = findViewById(R.id.totaltexto);

        btn_.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (subtotal_.getText().toString().isEmpty()) {
                    Toast.makeText(getApplicationContext(), "Llene Subtotal", Toast.LENGTH_LONG).show();
                } else if (igv_.getText().toString().isEmpty()) {
                    Toast.makeText(getApplicationContext(), "Llene IGV %", Toast.LENGTH_LONG).show();
                } else {
                    valor= Double.parseDouble(subtotal_.getText().toString()) *((Double.parseDouble(igv_.getText().toString())/100)+1);
                    total_.setText(valor+"");
                    Letras n = new Letras();
                    totaltexto_.setText(n.Convertir(valor+"",true));
                }
            }
        });


    }
}

 


2962 visitas

Sigue con el curso: Capítulo 14 – ImageView

Descarga el código del proyecto

Descarga el código fuente del proyecto adquiriendo el curso completo

Comprar

Más cursos que pueden interesarte

Más cursos

Codea Codea App

México, Colombia, España, Venezuela, Argentina, Bolivia, Perú

© Todos los derechos reservados Codea App | ...de frente al código!!! | 2020 - 2023