Round a submission value from SESSION + shortcode with 2 decimals

87 views Asked by At

Can someone explain me what is wrong with this AFTER line of code.

BEFORE (EXAMPLE - HOW TO USE):

"value" => "27.50" //enforce the use of strings

AFTER:

"value" => "round($_SESSION["Payment_Amount"], 2)" //Think of that Payment_Amount is 198,99 in session.

An explanation why it goes wrong would be very appreciated.

1

There are 1 answers

1
Don't Panic On BEST ANSWER

I would suggest using a formatting function like sprintf or number_format instead of round.

"value" => sprintf('%0.2f', $_SESSION["Payment_Amount"])

For two reasons:

  1. It will return a string. It looks like you're quoting the value because you need it to be a string.
  2. It will display two digits after the decimal point. It looks like that's what you want, and round won't show them if there happen to be trailing zeros, because it returns a float, and floats don't show trailing zeros when they're converted to strings.