Rey Norbert Besmonte
Rey Norbert Besmonte

Reputation: 791

PHP variable not showing 0 after multiplying

Im stuck at this part of my code. So I am trying to get the 30% of a specific value but I am not getting the right output. please see value below.

foreach($salary->getValues() as $key => $value) {
    echo 'salary:       '.$value['salary'];
    echo 'gross salary: '.$value['salary'] * .30;
}

lets assume that the salary array that we are getting is 40,000 (I am already getting this in my code) now multiply it .30 the answer must be 12,000. Therefore

Expected Output:

salary: 40,000 gross salary: 12,000

What is happening

salary: 40,000 gross salary: 12

Help please

Upvotes: 0

Views: 262

Answers (4)

Luke
Luke

Reputation: 640

"40,000" is a string. When trying to multiply, PHP tries to convert it to an integer, encounters the comma (,) and returns an error (but, oddly, then seems to continue the process using the int it got to before the comma)

One way would be to remove the comma before multiplying, then return it to number format after the multiplication.

$newSalary = number_format(str_replace("," , "", $value['salary']) * .30);

Upvotes: 1

use str_replace

foreach ($salary->getValues() as $key => $value) {
                    echo 'salary:       ' . $value['salary']; 
                    echo 'gross salary: ' . str_replace(',', '', $value['salary'] ) * .30 ;
                }
            }

Output : 1200

DEMO : https://3v4l.org/ZdQGZ

Upvotes: 2

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6329

Do not use this kind of "default formatting", but format any printed value yourself...

Try something like this:

foreach ($salary->getValues() as $key => $value) {
   printf( "salary: %.3f gross salary: %.3f\n", $value['salary'], $value['salary'] * .3 );
}

Upvotes: 0

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Just wrap the result of multiplication with money_format() method.

Reference: http://php.net/manual/en/function.money-format.php

Try something like money_format('%.3n', $value['salary'] * .30);

Upvotes: 0

Related Questions