yonan2236
yonan2236

Reputation: 13649

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.

Is there any formatting that needs to be done first here?

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

enter image description here

Upvotes: 1

Views: 1580

Answers (1)

Joey
Joey

Reputation: 354386

You are performing your calculation using integers, therefore the result is an int and converted to decimal on assignment. Since 1/3 is already 0 (in int arithmetic) multiplying it by 100 doesn't change anything there.

Use decimals instead:

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

The m suffix on a numeric literal makes it a decimal.

Incorporated a comment from Kay Zed:

If you are dealing with variables and not literals you can cast:

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

Upvotes: 7

Related Questions