Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert percentage string to double?

Tags:

c#

formatting

I have a string like "1.5%" and want to convert it to double value.

It can be done simple with following:

public static double FromPercentageString(this string value) {     return double.Parse(value.SubString(0, value.Length - 1)) / 100; } 

but I don't want to use this parsing approach.

Is any other approach with IFormatProvider or something like this?

like image 716
sashaeve Avatar asked Jan 31 '10 12:01

sashaeve


People also ask

How do you convert percent to float?

To convert a percent to a decimal, pass the percent string to the parseFloat() function and divide the result by 100 , e.g. parseFloat(percent) / 100 . The parseFloat() function parses the provided string and returns a floating point number. Copied!

How do I convert a number to a percent in C#?

var num = decimal. Parse( value. TrimEnd( new char[] { '%', ' ' } ) ) / 100M; This will ensure that the value must be some decimal number followed by any number of spaces and percent signs, i.e, it must at least start with a value in the proper format.

How do you convert a percentage in python?

percentage = str(round(x*100)) + '%' print(percentage)


2 Answers

It is culture sensitive, replace it like this:

  value = value.Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.PercentSymbol, ""); 

Then parse it.

like image 191
Hans Passant Avatar answered Sep 17 '22 13:09

Hans Passant


If you care about catching formatting errors, I would use TrimEnd rather than Replace. Replace would allow formatting errors to pass undetected.

var num = decimal.Parse( value.TrimEnd( new char[] { '%', ' ' } ) ) / 100M; 

This will ensure that the value must be some decimal number followed by any number of spaces and percent signs, i.e, it must at least start with a value in the proper format. To be more precise you might want to split on '%', not removing empty entries, then make sure that there are only two results and the second is empty. The first should be the value to convert.

var pieces = value.Split( '%' ); if (pieces.Length > 2  || !string.IsNullOrEmpty(pieces[1])) {      ... some error handling ...  } var num = decimal.Parse( pieces[0] ) / 100M; 

Using Replace will allow you to successfully, and wrongfully IMO, parse things like:

  • %1.5
  • 1%.5
  • 1.%5

in addtion to 1.5%

like image 39
tvanfosson Avatar answered Sep 19 '22 13:09

tvanfosson