vitto
vitto

Reputation: 19476

PHP: Converting an url variable number to a number

I'm trying to send a number from a page to another on in order to save it on my database, but when I use number_format method the number is converted to 0:

<?php
    $_REQUEST["myNumber"]; // the number from the url is 25%2C8 (25,8)
    // why this returns 0? 
    number_format (urlencode($_REQUEST["myNumber"]), 2, ".", "");
?>

I thought urlencode function was useful to convert url numbers to string numbers, where's my fault?

Upvotes: 0

Views: 1079

Answers (2)

coltraneofmars
coltraneofmars

Reputation: 221

number_format expects a number (float, to be exact) as the first argument, and the '25,8' won't be recognized as float. You'd need to do something like:

str_replace(',','.', $_REQUEST["myNumber"]); // '25,8' --> '25.8'

to convert a single comma to a string that can be evaluated as decimal number (which can be stored in db).

Running:

print number_format('25,8', 2);

returns 25.00 which is not 25.80 (which I assume is your desired result).

Upvotes: 0

Andrew
Andrew

Reputation: 8480

You need to use urldecode function instead of urlencode if you want to decode characters. And pass ',' as decimal pointer.

So your code should looks like this:

number_format (urldecode($_REQUEST["myNumber"]), 2, ",", "");

But you need to take to account that variables in $_POST\GET\REQUEST arrays is already decoded. Perhaps, your code may be even simpler:

number_format ($_REQUEST["myNumber"], 2, ",");

Upvotes: 2

Related Questions