user3529414
user3529414

Reputation: 15

PHP Format Number For Display and Insert to DB

I'm retrieving values from MySQL numeric field and want to format with a comma separator for 1000s like this: 21,000

This code below seems to work for display - how do I strip out the commas again before updating and inserting into MySQL DB?

<input type="text" name="Price id="Price value="<?php echo number_format($row_['Price'])); ?>" size="10" />

Thanks .........

Upvotes: 0

Views: 1850

Answers (2)

Juri Salminen
Juri Salminen

Reputation: 151

Not sure I understood your question correctly, but you could remove the character with str_replace...

str_replace(",", "", $Price);

Upvotes: 0

Fluffeh
Fluffeh

Reputation: 33502

You can use the numberFormatter class for both making and stripping the formatting around values quite nicely:

You can format easily with format()

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$data = numfmt_format($fmt, 1234567.891234567890000);
if(intl_is_failure(numfmt_format($fmt))) {
    report_error("Formatter error");
}
?>

Output

1.234.567,891

Then, the parse() function will let you remove whatever formatting you applied to get back to your original format.

<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo numfmt_parse($fmt, $num)."\n";
echo numfmt_parse($fmt, $num, NumberFormatter::TYPE_INT32)."\n";
?>

Output:

1234567.891

Note: Keep in mind that if you are passing these things in forms and back and forth, you will potentially lose decimal places or the like if you format them down.

Upvotes: 1

Related Questions