substr 以逗号生效
Substr take effect with comma
我有输入"Weight: 123,4 kg"
我想将号码保存到数据库中。所以我有这样的代码 substr
$_POST['product_weight'] =
substr($_POST['product_weight'], 8, 3);
str_replace(',','',$_POST['product_weight']);
但现在的问题是,输出总是“123.00”。是 substr 还是数据类型的错误?
我的表格
<input type="text" class='numbering' name="product_weight" value="<?=(!empty($form['product_weight']))?number_format($form['product_weight'],2):''?>">
输出
<td><?=(!empty($each->product_weight))?number_format($each->product_weight,2).' gr':'-';?></td>
此代码 substr($_POST['product_weight'], 8, 3)
表示 "return 3 characters starting at index 8 in the $_POST value" - 因此您捕获的只是 123,而不是值的小数部分。
试试这个,如果你的逗号是小数点参考这个Converting a number with comma as decimal point to float
逗号作为小数点,live demo.
<?php
$string = 'Weight: 123,4 kg';
echo number_format(floatval(str_replace(',', '.', substr($string, 8))),2);
逗号作为分隔符,live demo
<?php
$string = 'Weight: 123,4 kg';
echo number_format(floatval(str_replace(',', '', substr($string, 8))),2);
$string = 'Weight: 123,4 kg';
$arr_string = explode(" ", $string);
echo $arr_string['1']; //Output : 123,4
echo str_replace(",", ".", $arr_string['1']); //Output : 123.4
我有输入"Weight: 123,4 kg" 我想将号码保存到数据库中。所以我有这样的代码 substr
$_POST['product_weight'] =
substr($_POST['product_weight'], 8, 3);
str_replace(',','',$_POST['product_weight']);
但现在的问题是,输出总是“123.00”。是 substr 还是数据类型的错误?
我的表格
<input type="text" class='numbering' name="product_weight" value="<?=(!empty($form['product_weight']))?number_format($form['product_weight'],2):''?>">
输出
<td><?=(!empty($each->product_weight))?number_format($each->product_weight,2).' gr':'-';?></td>
此代码 substr($_POST['product_weight'], 8, 3)
表示 "return 3 characters starting at index 8 in the $_POST value" - 因此您捕获的只是 123,而不是值的小数部分。
试试这个,如果你的逗号是小数点参考这个Converting a number with comma as decimal point to float
逗号作为小数点,live demo.
<?php
$string = 'Weight: 123,4 kg';
echo number_format(floatval(str_replace(',', '.', substr($string, 8))),2);
逗号作为分隔符,live demo
<?php
$string = 'Weight: 123,4 kg';
echo number_format(floatval(str_replace(',', '', substr($string, 8))),2);
$string = 'Weight: 123,4 kg';
$arr_string = explode(" ", $string);
echo $arr_string['1']; //Output : 123,4
echo str_replace(",", ".", $arr_string['1']); //Output : 123.4