PHP remove decimal from number string

18,613

Solution 1

$one = '.57';
$two = str_replace('.', '', $one);
echo $two;

That works. 100% tested. BTW, all ereg(i)_* functions are depreciated. Use preg_* instead if you need regex.

Solution 2

Method       Result   Command
x100         57       ((float)$one * 100))
pow/strlen   57       ((float)$one * pow(10,(strlen($one)-1))))
substr       57       substr($one,1))
trim         57       ltrim($one,'.'))
str_replace  57       str_replace('.','',$one))

Just shwoing some other methods of getting the same result

Solution 3

$number = ltrim($number, '.');

That removes all trailing dots.

Solution 4

You say you've tried using str_replace without any luck, but the following code works perfectly:

<?php
    $one = '.57';
    $two = str_replace('.', '', $one);
    echo $two;
?>

Solution 5

I have used eregi_replace and str_replace and neither worked!

Well... ereg_replace() won't work cause it's using regular expresions, and . (dot) character has a special meaning: everything (so you've replaced every character into "" (the empty string)).

But str_replace() works absolutely fine in this case.

Here's a live test: http://ideone.com/xKG7s

Share:
18,613
DonJuma
Author by

DonJuma

Server Administrator Web Developer

Updated on June 06, 2022

Comments

  • DonJuma
    DonJuma almost 2 years

    i have an algorithym that gives back a number with a decimal point (I.E. ".57"). What I would like to do is just get the "57" without the decimal.

    I have used eregi_replace and str_replace and neither worked!

    $one = ".57";
    $two = eregi_replace(".", "", $one);
    print $two;