I am using a payment service that requires all it's charges be submitted as a whole number as such:
$205.01 submitted as 20501
$195.43 submitted as 19543
$42.06 submitted as 4206
I tried this first:
Convert.ToInt32(OrderTotal * 100);
But I found if OrderTotal = $120.01
then I ended up with 12000
, with the hundreds place rounded. What I wanted to end up with is 12001
. How do I perform this conversion without rounding?
decimal firstDecimal = 120.01M;
double firstDouble = 120.01;
float firstFloat = 120.01F;
Console.WriteLine ((int)(firstDecimal * 100)); // 12001
Console.WriteLine ((int)(firstDouble * 100)); // 12001
Console.WriteLine ((int)(firstFloat * 100)); // 12001
Console.WriteLine (Convert.ToInt32(firstDecimal * 100)); // 12001
Console.WriteLine (Convert.ToInt32(firstDouble * 100)); // 12001
Console.WriteLine (Convert.ToInt32(firstFloat * 100)); // 12001
This means one thing.... you have something else going wrong with your code.
EDIT:
Convert.ToInt32 produces the exact same result
Your code is correct as per my view. If the OrderTotal is 120.01 then total = 120.01*100 = 12001.
double OrderTotal = 120.01;
int total = Convert.ToInt32(OrderTotal * 100);
You can multiply it by 100 then cast it as an it
(int)decaimalValue * 100
decimal firstDecimal = 120.01M;
private int ConvertDecimalToInt(decimal value, short decimals)
{
if (decimals == 0) return (int)value;
int valueInt = (int)(value * (decimal)Math.Pow(10, decimals));
return valueInt;
}
Console.WriteLine(ConvertDecimalToInt(firstDecimal, 2)); // 12001