开发者

Values are incorrect while using String.Format

开发者 https://www.devze.com 2023-04-09 03:35 出处:网络
I 开发者_如何学Goneed to convert a decimal value into something like 0.3 = USDC000000000030 The code i wrote is as below.

I 开发者_如何学Goneed to convert a decimal value into something like

0.3 = USDC000000000030

The code i wrote is as below.

   transactionAmount = String.Format("USDC{0}", ((int)(amount*100)).ToString("D12"));

However, it is working for some values perfectly like the example given above. For other some values it is conversion is wrong for example

0.9 = USDC000000000089

1 = USDC000000000099

1.1 USDC000000000109

Any idea why is it happening so?

Thanks in advance


You're probably using double, which for financial values is a huge mistake.

Use decimal instead, and wash your troubles away.

To wit:

decimal amount = 0.3m;
string s = String.Format("USDC{0:000000000000}", 100 * amount);
Console.WriteLine(s);

Output:

USDC000000000030

Note that the language specification states:

The decimal type is a 128-bit data type suitable for financial and monetary calculations.


Try this instead:

String.Format("USDC{0:D12}", (int)(Convert.ToDecimal(amount) * 100));

Tested with the following:

  • 0.90 = USDC000000000090
  • 1.00 = USDC000000000100
  • 0.89 = USDC000000000089
  • 0.84 = USDC000000000084
  • 1.10 = USDC000000000110
0

精彩评论

暂无评论...
验证码 换一张
取 消