简体   繁体   English

我如何将此int转换为十进制格式

[英]How would I convert this int to decimal format

Sorry if this is a noob question, but I can't recall ever having to do this before and the solution escapes me in C#. 抱歉,如果这是一个菜鸟问题,但我想不起来以前曾经做过,而解决方案使我无法使用C#。 say I have two values; 说我有两个价值观;

int BeforeDecimal = 50000;
int AfterDecimal = 25;

How would I add these two int's to equal 50000.25m? 如何将这两个int相加等于50000.25m?

Adding int's wouldn't work, I need to be able to say to the int 25 to shift it's decimal places when adding it to BeforeDecimal. 添加int无效,我需要能够对int 25说,将其添加到BeforeDecimal时将其小数位移位。 Also I cannot convert to a string since I need this to be a decimal. 我也不能转换为字符串,因为我需要将此字符串设置为十进制。 I suppose I could hack this to a string then convert to a decimal, but that just plain wrong. 我想我可以将其修改为字符串,然后转换为十进制,但这只是错误的。

If AfterDecimal will always be 2 places, you can divide by 100 and add them together. 如果AfterDecimal始终是2位,则可以除以100,然后将它们加在一起。

If it won't, use 如果没有,请使用

return (decimal)BeforeDecimal + ((decimal)AfterDecimal / (decimal)Math.Pow(10, Math.Ceiling(Math.Log10(AfterDecimal))));

Just divide AfterDecimal by 100 and sum to BeforeDecimal. 只需将AfterDecimal除以100,然后将其加到BeforeDecimal。 The only thing to be aware is the Suffix m (for decimal) to let the language know that you want a floating point division and not an integer division. 唯一需要注意的是后缀m (十进制),使语言知道您需要浮点除法而不是整数除法。

decimal result = BeforeDecimal + (AfterDecimal / 100m);
decimal result = Convert.ToDecimal(BeforeDecimal) + (Convert.ToDecimal(AfterDecimal) / 100);
private decimal buttonOk_Click(int b, int a)
{
     return (decimal) b + ((decimal) a / 100.0));
}

Not the fastest solution, but how about: 不是最快的解决方案,但是如何:

decimal result = Decimal.Parse(String.Format("{0}.{1}", 
                 BeforeDecimal, AfterDecimal), CultureInfo.InvariantCulture);

You will avoid possible lose of precision of Pow , Ceil and division. 您将避免PowCeil和除法的精度损失。 In addition, it doesn't care how many digits you have after dot . 另外,它并不关心之后的位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM