Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change comma to dot, working with decimals in php

Tags:

php

So i have some fields coming from the form. Here you can type 0.3 and it will insert 0.3 in to the database. Do you type 0,3 it will just insert "0".

$product['protein']; // 0,3

So to this above how can i replace a comma with a dot ?

like image 843
Karem Avatar asked Sep 18 '11 12:09

Karem


People also ask

How do you change a decimal separator from a comma to a dot?

Click File > Options. On the Advanced tab, under Editing options, clear the Use system separators check box. Type new separators in the Decimal separator and Thousands separator boxes.

How can I get 2 decimal places in PHP?

Use sprintf() Function to Show a Number to Two Decimal Places in PHP.


1 Answers

Try PHP's function str_replace():

$product['protein'] = str_replace(',', '.', $product['protein']);

Which should be a good fit.

You could think to use number_format():

number_format($value, $numberOfDecimals, $charaForDecimalPoint, $charForThousandsSeparator)

but in your case it wouldn't apply, due to the fact that your starting value ("0,3") wouldn't be recognized as a number. In fact, the decimal point for a numeric value must be a dot(".").

Use number_format only if your starting value is a true number.

like image 145
genesis Avatar answered Sep 20 '22 12:09

genesis