将十进制转换为整数而不会丢失货币值 [英] Convert decimal to integer without losing monetary value

查看:62
本文介绍了将十进制转换为整数而不会丢失货币值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一项付款服务,要求将其所有费用均作为一个整数提交:

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

我首先尝试了这个:

Convert.ToInt32(OrderTotal * 100);

但是我发现如果 OrderTotal = $ 120.01 ,那么我最终得到了 12000 ,并把几百位四舍五入.我最后想要的是 12001 .如何不进行四舍五入而执行此转换?

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.

Convert.ToInt32产生完全相同的结果

Convert.ToInt32 produces the exact same result

这篇关于将十进制转换为整数而不会丢失货币值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆