How to get the exact value of the division with the decimals after the comma? [duplicate]

1

I need to do a percentage calculation, but I am not able to recover the exact value.

Example:

int valorUni = 8;

int valorTotal = 116;

double result;

result = (valorUni / valorTotal) * 100;
//Resultado esperado: 7,547169811320755
//Resultado que saí: 7
    
asked by anonymous 08.11.2018 / 14:08

1 answer

4

Making a cast :

using static System.Console;

public class Program {
    public static void Main() {
        int valorUni = 8;
        int valorTotal = 116;
        double result = ((double)valorUni / valorTotal) * 100;
        WriteLine(result);
    }
}

See running on ideone . And in Coding Ground . Also I placed GitHub for future reference .

If you split two integers, the result can only be integer, so you need to transform at least one of them into double so that the result has decimal places.

But note that it looks like you're working with monetary value. double should not be used for monetary value. See What is the correct way to use float, double, and decimal types? .

In any case, it is not to give the result you are expecting.

    
08.11.2018 / 14:11