Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - Convert decimal to integer without losing monetary value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...