Code displaying decimal value in C# for Java/Android

Asked

Viewed 127 times

1

I have a code that rounds up a value like decimal for homes I want, and would like to implement it on Android in Java however I’m having some difficulties, follows below the code in C#.

public static class Valor
{
    public static decimal Arredondar(decimal valor, int casasDecimais)
    {
        var valorNovo = decimal.Round(valor, casasDecimais);
        var valorNovoStr = valorNovo.ToString("F" + casasDecimais, CultureInfo.CurrentCulture);
        return decimal.Parse(valorNovoStr);
    }

    public static decimal? Arredondar(decimal? valor, int casasDecimais)
    {
        if (valor == null) return null;
        return Arredondar(valor.Value, casasDecimais);
    }
}

From what I researched I would have to use Bigdecimal but I’m having several problems.

  • 3

    We can help if you tell us what the problems are. You don’t seem to have problems, although I don’t know if you need all this. I don’t know what the objective is. Doesn’t seem to need BigDecimal.

1 answer

1


I’m not sure what the point is, but you don’t seem to need the BigDecimal (but something on the Java side, but C# is C#). O Decimal no rounding problems. Actually it seems to me to be much simpler to round than what is in this code. Unless you have some goal that’s not in the question:

public static decimal Arredondar(decimal valor, int casasDecimais) => decimal.Round(valor, casasDecimais);

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

It’s so simple that I don’t even think you need this method.

I do not see why would have difference on Android. Do not mix the dice with the data presentation.

For the voidable, there is a way to use the same method, as long as you use the operator of null Propagation of C# 6. For the unbreakable, you do not need to use this method, but if you want to use it to maintain consistency, ok. For this I used extension method.

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • I really checked here and managed to do without the Bigdecimal, Thanks bigown.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.