开发者

PHP remove decimal from number string

开发者 https://www.devze.com 2023-02-05 07:43 出处:网络
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 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 ne开发者_开发知识库ither worked!

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


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


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


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

That removes all trailing dots.


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


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


This would return as an integer.

$two = (integer) trim('.', $one);
0

精彩评论

暂无评论...
验证码 换一张
取 消