Gayan
Gayan

Reputation: 2935

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.

Upvotes: 0

Views: 1145

Answers (8)

josiie cayton
josiie cayton

Reputation: 13

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

Upvotes: 0

Paresh Thummar
Paresh Thummar

Reputation: 928

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);

Upvotes: 0

kpmDev
kpmDev

Reputation: 1370

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

Upvotes: 2

user1699797
user1699797

Reputation:

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)

Upvotes: 0

a1an
a1an

Reputation: 61

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;
?>

Upvotes: 1

srain
srain

Reputation: 9112

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 ,

Upvotes: 0

ReNiSh AR
ReNiSh AR

Reputation: 2852

the best way is:

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

Upvotes: 0

leo108
leo108

Reputation: 817

you can simply replace ',' with ''

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

Upvotes: 0

Related Questions