3
How can I get the number of decimals of a variable decimal
?
Ex.: If I receive the number:
4.5 - you must return 1
5.65 - you must return 2
6.997 - must return 3
I know what you can do by converting to string
, something like:
decimal CasasDecimais(decimal arg){
return arg.ToString().Substring(arg.ToString().LastIndexOf(",") + 1).Length;
}
And I’ve also seen that question of the Soen, but I would like to receive alternatives to these two forms.
I believe that the solution always involves transforming into strings, because floating point numbers cannot represent values like 0.2 or 0.1 exactly. If you use pure mathematics, you will find 15 decimal places because the value the computer sees is 0.1999999999999 or 0.1000000000000001. Rounding to a number of decimals less than 15 (according to what the application requires - could be 2, 5, 10...) and checking where zeroes start is an option.
– epx
Yeah, I actually have my doubts whether
double
it is possible to hit even with string. But the question was changed todecimal
.– Maniero
There is only one detail that needs to be corrected in this code, the way it is it is dependent on OS settings to work, exactly so it would give error in most computers in Brazilian Portuguese since they use by default the comma as decimal separator, but it is simple to correct by changing the
ToString()
forToString(CultereInfo.InvariantCulture)
– Leandro Godoy Rosa
@Leandrogodoyrosa you’re right, edited, thank you.
– Maniero