Convert decimal to integer without losing monetary

2019-10-23 03:18发布

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?

4条回答
Lonely孤独者°
2楼-- · 2019-10-23 03:39
    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
查看更多
Juvenile、少年°
3楼-- · 2019-10-23 03:45
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

查看更多
beautiful°
4楼-- · 2019-10-23 03:48

You can multiply it by 100 then cast it as an it

(int)decaimalValue * 100
查看更多
放我归山
5楼-- · 2019-10-23 03:55

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);
查看更多
登录 后发表回答