4

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;
DonJuma
  • 2,028
  • 13
  • 42
  • 70
  • 1
    sorry, we will need more exact specifications about input and output... – Paul Jan 19 '11 at 18:30
  • 1
    possible duplicate of [How to remove the first character in php](http://stackoverflow.com/questions/4638569/how-to-remove-the-first-character-in-php) – Gordon Jan 19 '11 at 18:31
  • Is the decimal point always at the beginning? – Jonah Jan 19 '11 at 18:34

6 Answers6

8
$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.

Jonah
  • 9,991
  • 5
  • 45
  • 79
5
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

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
2
$number = ltrim($number, '.');

That removes all trailing dots.

NikiC
  • 100,734
  • 37
  • 191
  • 225
1

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;
?>
John Parker
  • 54,048
  • 11
  • 129
  • 129
1

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

Crozin
  • 43,890
  • 13
  • 88
  • 135
0

This would return as an integer.

$two = (integer) trim('.', $one);
Matt Lowden
  • 2,586
  • 17
  • 19