1

If have a small question, I think.

I succesfully used the code from this answer on a certain question: Get DIV content from external Website

It works great. The output I have is for example 9,1. Now I want to make this a percentage, so it should be 91%.

$second_step[0] gives 9,1.

I used the following code to make it a percentage:

$score = $second_step[0] * 10;

...but this outputs 90 instead of 91.

What I'm doing wrong? It looks like a simple code, but I'm not sure why it outputs 90 instead of 91.

Hopefully someone can help me with this.

Sorry for my bad English :)

Community
  • 1
  • 1

4 Answers4

2

Try this

$val = floatval(str_replace(',', '', $second_step[0]));
Sanith
  • 681
  • 7
  • 13
1

Probably related to the number format. Your example shows 9[comma]1, which PHP would see as string and upon calculation it returns the first number part the script encounters (which is just 9). If you want to do math operations, you need to convert it to a number (reading 9[period]1).

$score = floatval(str_replace(',', '.', $second_step[0])) * 10;
Paul
  • 8,974
  • 3
  • 28
  • 48
  • Thank you for your quick response! Can you show me how to convert it to a number? I'm not sure how I can handle this. –  Sep 25 '14 at 07:29
0

You are getting 90 because it sees 10 as an int. So your ouput will be converted to an int.

try this: $score = $second_step[0] * 10.0; PHP sees 10 as an int, but 10.0 as a float. You could also cast 10 to a float by doing it like this: $score = $second_step[0] * floatval(10);

Both methods will work, but the first method will be the best.

andy
  • 341
  • 3
  • 11
0

Your $second_step is treated as integer, see http://php.net/manual/de/language.types.string.php#language.types.string.conversion unless you explicitely change the script's locale using setlocale().

IF the comma needs to stay there AND you did not change locale, you could for example do $temp = str_replace("," , "." , $setlocale[1]);

MBaas
  • 7,248
  • 6
  • 44
  • 61