Help calculating a percentage to two or three decimal places [Answered]RSS

4 replies

Last post Jul 05, 2017 05:59 PM by JBetancourt

• funluckykitt...

Participant

1125 Points

1683 Posts

Help calculating a percentage to two or three decimal places

Jun 30, 2017 03:10 PM|funluckykitty|LINK

I'm struggling with how to format a percentage that I'm calculating.  I can't figure out how to include the two decimal places.   For example, 99% should show as 98.56%.  What am I doing wrong that it's "dropping" the two or three decimal places?

`currentYearApprovedVPreviousYearApprovedPercentage = (Convert.ToDecimal(Replace(lookuplblTotalApprovedCurrentYearVApprovedPreviousYear.Text, "\$", "")) / Convert.ToDecimal(Replace(lookuplblTotalApprovedPreviousYear.Text, "\$", "")) * 100)`

--Susan
• JBetancourt

Participant

1360 Points

608 Posts

Re: Help calculating a percentage to two or three decimal places

Jun 30, 2017 07:25 PM|JBetancourt|LINK

try this code

```decimal StringToDecimal(string input){
return decimal.Parse(Regex.Replace(input, @"[^\d.]", ""));
}

var number1 = StringToDecimal(lookuplblTotalApprovedCurrentYearVApprovedPreviousYear.Text);
var number2 = StringToDecimal(lookuplblTotalApprovedPreviousYear.Text);

currentYearApprovedVPreviousYearApprovedPercentage = number2 == 0 ? 0 : Math.Round(number1*100/number2,2);
```

-----------------
Please remember to click "Mark as Answer" the responsES that resolved your issue.
• Eric Du

Contributor

6670 Points

2715 Posts

Re: Help calculating a percentage to two or three decimal places

Jul 03, 2017 06:35 AM|Eric Du|LINK

Hi funluckykitty,

According to your description and code, as far as I know, you need write the replace method like this(textbox1.text.replace("old character" , "new character");), here is the complete code, please check:

Sample Code:

``` string b = "\$100";//suppose this is textbox1 value
string c = "\$150";//suppose this is textbox2 value
var a = Math.Round((Convert.ToDecimal(b.Replace("\$", "")) / Convert.ToDecimal(c.Replace("\$", "")) * 100), 2)+ "%";
Response.Write(a);```

Best Regards,

Eric Du

MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.
• 0belix

Participant

1178 Points

785 Posts

Re: Help calculating a percentage to two or three decimal places

Jul 03, 2017 02:26 PM|0belix|LINK

Format(currentYearApprovedVPreviousYearApprovedPercentage, "n")

• JBetancourt

Participant

1360 Points

608 Posts

Re: Help calculating a percentage to two or three decimal places

Jul 05, 2017 05:59 PM|JBetancourt|LINK

did you resolved your issue?

-----------------
Please remember to click "Mark as Answer" the responsES that resolved your issue.