DogPooOnYourShoe
DogPooOnYourShoe

Reputation: 149

Converting standard numbers to decimal

Whenever I insert a value like: 1 into a decimal field it will immediately rejects it. Is there any code in PHP to convert a value of say "1" to "01.00" or "1.00"

Upvotes: 1

Views: 3553

Answers (5)

jeroen
jeroen

Reputation: 91734

You can cast a number to a float like for example:

$x = (float) $x;

or:

$x = floatval($x);

Upvotes: 1

shamittomar
shamittomar

Reputation: 46692

Yes, it's called number_format. A sample usage in your case:

echo number_format(1, 2, '.', '');

will echo 1.00. Now, to use it in query to insert, surround it with quotes and do it like this:

mysql_query("INSERT INTO tablename (Amount)
             VALUES ('" . number_format($your_number), 2, '.', '') . "')";

Upvotes: 2

bharath
bharath

Reputation: 1233

you can do this

$num = 1;
print number_format($num , 2);

Upvotes: 0

gaius_julius
gaius_julius

Reputation: 59

the right way to format any number to the desired string representation is the sprintf function: https://www.php.net/sprintf

Upvotes: 1

Brian H
Brian H

Reputation: 833

Why would it reject it? Are you wrapping it with quotes or something? Anyway, to convert, use the number_format() function.

Upvotes: 0

Related Questions