简体   繁体   中英

PHP- how to convert string to number?

How to convert this 19,500 string to number. If I do this

<?php

$val = "19,500";
$number = explode("," , $val);
$newnumber = $number[0].$number[1];

?>

But I don't think this is correct way.

LIVE DEMO

You can replace the string ',' to '' and then convert into integer by int

<?php

$number = "19,500";
$updatedNumber = str_replace(',','',$number);

echo (int)$updatedNumber ;

NOTE: int is better to use than intval function. It reduces overhead of calling the function in terms of Speed. http://objectmix.com/php/493962-intval-vs-int.html

Try this:

<?php
$val = "19,500";
$val = str_replace(',', '.', $val);
$number = (float)$val;
?>

UPDATED: if comma comes out as a thousands-separator then:

<?php
$val = "19,500";
$val = str_replace(',', '', $val);
$number = (int)$val;
?>

您只需将“,”替换为“

$newnumber = str_replace(',', '', $val);

the best way is:

<?php
  $val = "19,500";
  $tmp = str_replace(',', '', $val);
  $newnumber = (float)$tmp;
?>

I think you just want to remove the , :

<?php
$val = "19,500";
$val = strtr($val, array(',' => ''));
$number = intval($val);
var_dump($number);

use strtr() instead of str_replace() in case of multiple ,

Just try this code

$val = "19,500";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val)));  // output : 19500

$val = "19,500.25";
$newnumber = intval(str_replace(',', '', str_replace('.', '', $val)));  // output : 1950025

you can edit delimiter that want to replace with balnk string :)

Or you can try this

$newnumber = preg_match("/[^0-9,. -]/", $val) ? 0 : preg_replace("/[^0-9.-]/", "",$val);

When I see your code it's just sting string(5) "19500"

<?php
 $val = "19,500";
 $number = explode("," , $val);
 $newnumber = $number[0].$number[1];
 var_dump($newnumber);
?>

so you can convert to integer like the following

<?php
    $val = "19,500";
    $number = explode("," , $val);
    $newnumber = $number[0].$number[1];
    $realinteger = (int)($newnumber);
    var_dump($realinteger);
?>

So the result will be int(19500)

just try one. simple as that :)

<?php
$val = "19,500";
$val = str_replace(',','', $val);
$newnumber = number_format($val,2);

?>

OUTPUT: 19,500.00

  • If you want to have no decimal you can change the 2 in 0. Like this.

OUTPUT: 19,500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM