How to Convert Percentage String to Double

How to convert percentage string to double?

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%

I want to turn a percentage value string to double?

Maybe something like:

double value = double.Parse(p.TrimEnd(new[] {'%'}))/100;

What is a clean way to convert a string percent to a float?

Use strip('%') , as:

In [9]: "99.5%".strip('%')
Out[9]: '99.5' #convert this to float using float() and divide by 100

In [10]: def p2f(x):
....: return float(x.strip('%'))/100
....:

In [12]: p2f("99%")
Out[12]: 0.98999999999999999

In [13]: p2f("99.5%")
Out[13]: 0.995

Java 100% to number

Thank you for the posts and suggestions, I did try using the solution posted by eg04lt3r, however the result was translated. In the end I wrote a simple function that does exactly what I require. I'm sure a good regular expression would have also worked.

    public static double string2double(String strValue) {
double dblValue = 0;
if ( strValue != null ) {
String strResult = "";
for( int c=0; c<strValue.length(); c++ ) {
char chr = strValue.charAt(c);

if ( !(chr >= '0' && chr <= '9'
|| (c == 0 && (chr == '-' || chr == '+'))
|| (c > 0 && chr == '.')) ) {
break;
}
strResult += chr;
}
dblValue = Double.parseDouble(strResult);
}
return dblValue;
}

how to convert percentage String to BigDecimal?

BigDecimal d = new BigDecimal(percentage.trim().replace("%", "")).divide(BigDecimal.valueOf(100));

Convert percentage value to int

Use parseFloat

parseFloat('42.42%');// => float val = 42.42

Convert percent string to float in pandas read_csv

You can define a custom function to convert your percents to floats at read_csv() time:

# dummy data
temp1 = """index col
113 34%
122 50%
123 32%
301 12%"""

# Custom function taken from https://stackoverflow.com/questions/12432663/what-is-a-clean-way-to-convert-a-string-percent-to-a-float
def p2f(x):
return float(x.strip('%'))/100

# Pass to `converters` param as a dict...
df = pd.read_csv(io.StringIO(temp1), sep='\s+',index_col=[0], converters={'col':p2f})
df

col
index
113 0.34
122 0.50
123 0.32
301 0.12

# Check that dtypes really are floats
df.dtypes

col float64
dtype: object

My percent to float code is courtesy of ashwini's answer: What is a clean way to convert a string percent to a float?

Convert string percentage to double

As long as your string begins with a valid text representation of a floating-point number (it can only contain whitespace at the beginning), you can call doubleValue and omit any preprocessing of the string.

NSLog(@"value: %f", [@"    95.5%" doubleValue]); // --> value: 95.500000


Related Topics



Leave a reply



Submit