Error: can not convert from double to float

1

Why float is not accepted for the numbers 0.197 and 0.185?

Code:

float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}   

ent.close();
    
asked by anonymous 17.09.2018 / 05:02

1 answer

3

By default in java, floating-point literals are considered by the JVM to be double . You need to make explicit that that number is float, since the range of values of type double is larger than the float type, and the JVM does not auto cast in this case.

Just add a f to the side of the literal number, so you're explicitly stating that the literal value is also a float type:

float salBruto, salLiquido;

Scanner ent = new Scanner (System.in);
System.out.println("Informe o seu salário:");
salBruto = ent.nextFloat();

if (salBruto >= 1500 & salBruto <=2500) {
    salLiquido = salBruto + (salBruto * 0.197f);
} else {
    if (salBruto > 2500 & salBruto <= 5000) {
        salLiquido = salBruto + (salBruto * 0.185f);
    } else {
        if (salBruto < 1500 & salBruto > 5000) {
            salLiquido = salBruto;
        }
    }
}   
    
17.09.2018 / 14:28