简体   繁体   English

十进制值转换为字符串

[英]Decimal Value to String

Below computation should result to value of 33.3333333 but I'm not getting the right output in the message box when tying to display the value. 下面的计算应该得出33.3333333的值,但是在显示该值时我在消息框中没有得到正确的输出。

Is there any formatting that needs to be done first here? 这里需要先进行任何格式化吗?

decimal result = (1/3)*100;
MessageBox.Show(result.ToString());

在此处输入图片说明

You are performing your calculation using integers, therefore the result is an int and converted to decimal on assignment. 您正在使用整数执行计算,因此结果为int并在赋值时转换为decimal Since 1/3 is already 0 (in int arithmetic) multiplying it by 100 doesn't change anything there. 由于1/3已经是0 (以int算术),因此将其乘以100不会改变该值。

Use decimals instead: 请改用小数:

decimal result = (1m / 3m) * 100m;

The m suffix on a numeric literal makes it a decimal. 数字文字的后缀m使其为十进制。

Incorporated a comment from Kay Zed : 合并了Kay Zed的评论:

If you are dealing with variables and not literals you can cast: 如果要处理变量而不是文字,则可以强制转换:

 decimal result = ((decimal)a / (decimal)b) * 100m; 

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

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