Reputation: 478
i'm using $_POST
to 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
Reputation: 2911
<?php
$number = '1.000.000,00';
$replaced_number = str_replace(array('.',','), array('',''), $number);
echo number_format($replaced_number,2,'.','');
?>
Upvotes: 2
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
Reputation: 642
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
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
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