Welcome Guest, Not a member yet? Register   Sign In
Format decimal removing anything before the decimal point
#1

[eluser]jtotheb[/eluser]
I hate to ask questions like this on here but i really can't work it out and was hoping someone could tell me where i'm going wrong.

I've got a value of say "0.37" and i'd like to format the string to be just "37"

I've tried:
money_format()
sprintf()
printf()
strstr()
substr()

And i can't get it to do what i want, i can remove what's after the decimal fine, it's removing what's before the decimal i'm having trouble with!

Cheers!
#2

[eluser]gtech[/eluser]
im sure there is a better way but this would work:

$str = "0.37";
$numbers = explode('.', $str);
$before = $numbers[0];
$after = $numbers[1];

or you could use a regular expression.
#3

[eluser]jtotheb[/eluser]
Nice action, that's a good idea. Cheers!
#4

[eluser]TheFuzzy0ne[/eluser]
Multiplying it by 100 will shift the decimal place over to the right by two spaces. This won't work, however, if you have a number such as 0.376, which will generate 37.6.

Another solution might be to just use a regular expression. Something like:

Code:
$number = 0.37;
$pattern = '.+\.([0-9]+)';
if (eregi($pattern, $number, $matches)) {
    $number = $matches[1];
}
echo $number;

this will work no matter how many decimal places you have, however, if you are interested in only the first 2 decimal places, multiplying by 100, and then using floor() should work for you. Like this:

Code:
$number = 0.37;
$number = floor($number*100);
EDIT: You can also use ceil() or round(), depending on what exactly it is you need.
#5

[eluser]jtotheb[/eluser]
I did try floor pretty unsuccessfully i must admit. Thanks for that also!
#6

[eluser]hepp[/eluser]
A simpler way to just remove everything before the dot

Code:
<?php
$val = 0.37;
$val = substr($val, strpos($val, '.')+1); // $val is now 37
?>




Theme © iAndrew 2016 - Forum software by © MyBB