phphtmlklarna

Devide $price into partial payment (output issues over 1000 in amount)


Good Evening ppl.

Ive finished all coding for andvertising where I will show possible ways for customer to divide payment into 6 months. Everythings good, except I have issues with the output for new price when amount is more than 1000, I guess its because of the space?! in 1 000...?

This is the code: Pay over 6 months: <?php if ($price_calculate['price_wo_discount']>0) echo round( ($price_calculate['price_wo_discount'])*0.16); ?>


Solution

  • If you try to do something like this in PHP,

    echo round( '1 000' * 0.16);
    

    You would get Notice: A non well formed numeric value encountered in .... This is because PHP cannot safely cast the string into appropriate numeric value. It magically casts the string to 0 and throws a notice. That's why you get 0 output.

    Ideally you need to remove all spaces and commas from you numeric string, then possibly use the is_numeric function to determine if your string is actually numeric, then do round.

    Also implicit casting in you if ($price_calculate['price_wo_discount'] > 0 block might lead to some side effects. Consider this in PHP:

    var_dump('1 is number' > 0); //outputs true
    

    My advice: use value objects to validate your input first.