0

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

2
  • "40,000" is not a number. It's a string. PHP is trying to treat it as an integer but encounters the , and gives this error <b>Notice</b>: A non well formed numeric value encountered in <b>[...][...]</b> on line Commented Aug 30, 2017 at 4:21
  • try my answer, subukan mo sagot ko :D, with demo Commented Aug 30, 2017 at 4:33

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.