William Xavier
William Xavier

Reputation: 478

PHP format number before insert into database

i'm using $_POSTto send form values to PHP and then insert into database, i have some inputs for prices values that looks like this:

1.000.000,00 (1 million in BRL "Brazilian Real")

I need to convert it to 1000000.00 (DECIMAL(10,2) to insert into database)

How can i do that using PHP number_format()?

Thanks!

EDIT

If number_format() is not the function i'm looking for, what's best to be using in this case?

Also, i need help finding a solution, even if the user value is 100.000,00

Upvotes: 0

Views: 2687

Answers (5)

Md. Saidur Rahman Milon
Md. Saidur Rahman Milon

Reputation: 2911

<?php
$number  = '1.000.000,00';
$replaced_number = str_replace(array('.',','), array('',''), $number);
echo number_format($replaced_number,2,'.','');
?>

Upvotes: 2

Lelio Faieta
Lelio Faieta

Reputation: 6679

If you have a look at php.net you will easily see the right syntax for your goal: number_format($number,2,'.','') The first parameter is the number of decimal places that in your case is 2. The second is the symbol to use for decimal separator and the third is the one to be used for thousands that in your case will be nothing .

Upvotes: 0

Nikola Svitlica
Nikola Svitlica

Reputation: 642

  1. You can not do that with number format, it works other way around.
  2. The thing that you do is bad practice, View layer should send primitive data to Controller - if you are using some advanced javascript component to represent to the user formatted number, that is fine, but underlaying form control should send primitive data, i.e. 10000000.00

Now, if nothing that I have stated to you is not applicable at this particular moment, and having in mind that this format that you have send is fixed (dot for thousand separator, coma for decimal separator), you can clean the value by using simple str_replace.

But, the trick is to replace first dot with empty string, then coma with dot.

str_replace(',', '.',str_replace('.', '', $number));

Got it?

But know that what you are doing is bad approach and wrong implementation, eventually, it will bite you in the a**.

Upvotes: 3

Sky
Sky

Reputation: 4370

The easiest way is to use str_replace() function:

<?php
$p = '1.000.000,00';
$p = str_replace('.', '', $p);
$p = str_replace(',', '.', $p);
echo $p;

Upvotes: 2

Md. Saidur Rahman Milon
Md. Saidur Rahman Milon

Reputation: 2911

At first replace the (.) and (,) with str_replace by '' and then use t the following function

number_format($replaced_number,$decimal)

Upvotes: 0

Related Questions