简体   繁体   中英

Calculate percentage with PHP

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 :)

尝试这个

$val = floatval(str_replace(',', '', $second_step[0]));

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;

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.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM