4
I’m having trouble formulating a good means of extracting the decimal part of a variable decimal
, so far the existing implementation in the system is that:
public static bool getCasasDecimais(decimal val, out int result)
{
string[] split = val.ToString().Split('.');
return int.TryParse(split[split.Length-1], out result);
}
But it has a problem, it is necessary to adapt the code depending on the culture in which the program is running because of the division of the number by the decimal point.
I’m trying to find some other implementation to pull that part of the number, preferably something that doesn’t manipulate a string
to carry out such an operation. The only way that came to mind was using Truncate
:
decimal number = 12.5523;
var x = number - Math.Truncate(number);
But for some reason, this implementation doesn’t seem very robust, I don’t really know why, but I would like to see other possible implementations before deciding which one to use.
After a user comment star in the question, I decided to re-test the implementation specified above and it does not return the expected value, since I wish to have the decimal digits in an integer, not just the decimal part.
Exemplo: 45.545
Resultado esperado: 545
Resultado proveniente da implementação com Math.Truncate: 0.545
The doubt continues, there is a way to receive this value without manipulating the number as string?
If the input is
123.456
, you want the result to be456
or0.456
?– dcastro
the expected result is
456
, and now testing the implementation using theTruncate
it won’t even work because it will return0.456
– Marciano.Andrade
'Cause :/ I think the best thing is to use the invariant culture.
– dcastro