Search code examples
phpmysqlnumber-formattingsubstr

Substr take effect with comma


I have input "Weight: 123,4 kg". I want to save the number to the database so I use substr like this

 $_POST['product_weight'] = 
substr($_POST['product_weight'], 8, 3);
str_replace(',','',$_POST['product_weight']);  

But the problem now is that the output is always "123.00". It was a mistake from substr or data type?

My form

<input type="text" class='numbering' name="product_weight" value="<?=(!empty($form['product_weight']))?number_format($form['product_weight'],2):''?>">

Output

<td><?=(!empty($each->product_weight))?number_format($each->product_weight,2).' gr':'-';?></td>

Solution

  • Try this, if you comma is for decimal point refer to this Converting a number with comma as decimal point to float

    comma as decimal point, live demo.

    <?php
    $string = 'Weight: 123,4 kg';
    echo number_format(floatval(str_replace(',', '.', substr($string, 8))),2);
    

    comma as seperator, live demo

    <?php
    $string = 'Weight: 123,4 kg';
    echo number_format(floatval(str_replace(',', '', substr($string, 8))),2);