Display decimal places (Currency) is rounding

5

I have an application where the price should go in int format without decimals.

int Valor = (int)(produto.Valor * 100); //o produto.Valor é um decimal

The problem is when I want to display this value in View

For products like 0.10 it displays 0

int Valor = (int)(produto.Valor * 100);

Value is 10, equivalent to 0.10 (perfect here)

I tried:

@{
decimal Valor = Model.ValorExibicao / 100; //ValorExibicao é um int
}
@Valor.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("pt-br"))

Shows $ 0.00

I tried:

@Convert.ToDouble(Model.ValorExibicao/ 100);

Displays 0 Only @Model.ValorExibicao shows the correct 10 (equivalent to 0.10)

I could create in viewModel the correct value without formatting, however I think it would be a trick to get around an error of mine.     

asked by anonymous 12.04.2016 / 18:41

2 answers

2

The solution is very simple:

Model.ValorExibicao / 100M

This ensures that the division will be done in decimal, since the suffix M indicates a decimal. If you want to apply a ToString() , a string.Format() , or an interpolated string >, or another way to format the display, the decimal places, is at your discretion, the calculation will be right this way.

Never use double for monetary values or others that can not have rounding problems.

    
12.04.2016 / 21:01
3

There are other ways to get the same result, like everything else in programming. You can Cast explicit for decimal . Use the decimal.Parse () to convert the values (much used when the value is string ). You can also use Convert.ToDecimal () . These three options will return the integer value with decimal places.

Below is an example of how to use each of the forms mentioned above:

public static void Main()
{
    int valor = 10;
    string valorString = "10";

    decimal valorNormal = valor/100;

    decimal valorCast = (decimal)valor/100;

    decimal valorParse = decimal.Parse(valorString)/100;

    decimal valorConvert = Convert.ToDecimal(valor)/100;

    Console.WriteLine("Valor Normal: " + valorNormal);
    Console.WriteLine("Cast explítico: " + valorCast);
    Console.WriteLine("Parse: " + valorParse);
    Console.WriteLine("Converto to: " + valorConvert);

}

Example running on dotNetFiddle.

    
13.04.2016 / 19:21