PHP - Transform String to Float - php

I need to transform a String to a Float.
I will receive Strings like this:
$string = "1.70 m";
$string2 = "2.445 m";
How can I easly transform this strings to:
$float1 = 1.70;
$float2 = 2.445;
Can someone give me some clues?
Best Regards,

Those are floats, not integers. Integers do not have decimal points.
To answer your question, you can simply typecast the strings directly, the conversion will strip off the units as those aren't numeric characters:
$string = "1.70 m";
$float = (float) $string;

you can get it by
echo (float)array_shift(implode(' ', $string));
Update :
echo (float) $string;

The easiest way to do this is probably with the floatval() function:
http://ca.php.net/manual/en/function.floatval.php
For exmaple:
floatval("1.70 m");
gives you:
1.7

$integer = intval($string);
Enjoy :D

Related

how to get value before and behind decimal point in string

My PHP file receives (via $_POST) strings (with constant prefix) like:
(constant prefix in this example = 'astring'; figure before and after the decimal point can vary in size)
astring1.1
astring1.2
..
astring23.2
astring23.6
How to get the value behind the decimal point? I know how to extract the total figure from the constant prefix, but I need to use the figures before and after the decimal point and don't know how to extract those. Using preg_match in some way?
If you want the number before the decimal. Try This.
$number = 2.33;
echo floor($number);
Try with explode like
$str = 'astring23.2';
$str_arr = explode('.',$str);
echo $str_arr[0]; // Before the Decimal point
echo $str_arr[1]; // After the Decimal point
list($before, $after) = explode(".", $string);
echo "$before is the value before the decimal point!";
echo "$after is the value after the decimal point!";
A simple way (php 5.3+):
$str = 'astring23.2';
$pre = strstr($str, '.', true);
Do you want something similar?
<?php
$string = "astring23.6";
$data = explode("astring", $string); // removed prefix string "astring" and get the decimal value
list($BeforeDot, $afterDot)=explode(".", $data[1]); //split the decimal value
echo "BeforeDot:".$BeforeDot." afterDot: ". $afterDot;
?>
If you want only numbers, use like this
$str = 'astring23.2';
$str_arr = explode('.',$str);
echo preg_replace("/[a-z]/i","",$str_arr[0]); // Before the Decimal point
echo $str_arr[1]; // After decimal point

Trimming trailing zeros WITHOUT casting to float

Let's try again but a bit more explicitly.
I am printing numbers to the screen and want to make them more friendly to users by stripping off trailing zeros after the decimal point. I have tried casting to a float but this solution is not a good fit as I handle numbers like 0.00000001 which come out along the lines of 0.1-e7 sort of thing which is unfriendly to end users.
I need a solution where number like the following...
12.02000000
12.00000000
0.00000001
...can be printed to the screen like...
12.02
12
0.00000001
Using rtim kills numbers like 10000. number_format needs to know the number of decimal places which may be from 0 to 8. Casting to float does not work. I'm sure that there is some regex for this.
Here is the regex solution as you want:
$repl = preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', $numstr);
Testing:
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '12.02000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '12.00000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '0.0000000100000000') . "\n";
echo preg_replace('/(?>\.0+$|(\.\d*[^0])0+$)/', '$1', '100000000') . "\n";
Output:
12.02
12
0.00000001
100000000
A slightly simpler solution:
preg_replace("/(\.0*[^0]+)0*|\.0*/", '\1', $number)
After a bit of search for internet i found something that could be useful:
function floattostr( $val )
{
preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
}
This will give you the output you need i guess
I found here
Here is a non-regex way to do it:
if (strpos($number, '.') !== false) {
$number = rtrim($number, '.0');
}
Ternary operator style:
$number = strpos($number, '.') !== false ? rtrim($number, '.0') : $number;

PHP remove commas from numeric strings

In PHP, I have an array of variables that are ALL strings. Some of the values stored are numeric strings with commas.
What I need:
A way to trim the commas from strings, and ONLY do this for numeric strings. This isn't as straightforward as it looks. The main reason is that the following fails:
$a = "1,435";
if(is_numeric($a))
$a = str_replace(',', '', $a);
This fails because $a = "1435" is numeric. But $a = "1,435" is not numeric. Because some of the strings I get will be regular sentences with commas, I can't run a string replace on every string.
Do it the other way around:
$a = "1,435";
$b = str_replace( ',', '', $a );
if( is_numeric( $b ) ) {
$a = $b;
}
The easiest would be:
$var = intval(preg_replace('/[^\d.]/', '', $var));
or if you need float:
$var = floatval(preg_replace('/[^\d.]/', '', $var));
Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)
It sounds like the ideal solution for what you're looking for is filter_var():
$a = filter_var($a, FILTER_VALIDATE_FLOAT, FILTER_FLAG_ALLOW_THOUSAND);
(Note that it's using FILTER_VALIDATE_FLOAT instead of FILTER_VALIDATE_INT because that one doesn't currently have a FILTER_FLAG_ALLOW_THOUSAND option).
Try this .this worked for me
number_format(1235.369,2,'.','')
if you use number_format like this
number_format(1235.369,2) answer will be 1,235.37
but if you use like below
number_format(1235.369,2,'.','') answer will be 1235.37
it's removing the "," of "1,235.37"
function cleanData($a) {
if(is_numeric($a)) {
$a = preg_replace('/[^0-9,]/s', '', $a);
}
return $a;
}
If you want to remove commas from numbers inside a string that also contains words, the easiest way I think would be to use preg_replace_callback:
Example:
$str = "Hey hello, I've got 12,500 kudos for you, spend it well"
function cleannr($matches)
{
return str_replace("," , "" , $matches["nrs"]);
}
$str = preg_replace_callback ("/(?P<nrs>[0-9]+,[0-9]+)/" , "cleannr" , $str);
Output:
"Hey hello, I've got 12500 kudos for you, spend it well"
In this case the pattern (regex) differs from the one given in the accepted answer since we don't want to remove the other commas (punctuation).
If we'd use /[0-9,]+/ here instead of /[0-9]+,[0-9]+/ the output would be:
"Hey hello I've got 12500 kudos for you spend it well"
How about this:
/**
* This will parse the money string
*
* For example 1, 234, 456.00 will be converted to 123456.00
*
* #return
*/
function parseMoney(string $money) : float
{
$money = preg_replace('/[ ,]+/', '', $money);
return number_format((float) $money, 2, '.', '');
}
Example;
parseMoney('-1, 100, 000.01'); //-1100000.01

PHP replace string

$string = 'http://site.com/category/1/news/2134/'; // '1' is dynamic
How can I change 1 to any number I want?
Can't call parts of the string, its just a text-like variable.
It can be done with some true regex.
$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);
This replaces the number by 56.
This approach uses a regex with assertions.
$array = explode('/',$string);
$array[4] = '666';
$string = implode('/',$array);
[edit]
#People downvoting, what seems to be the problem with this approach?
Without more information, my best guess at your problem is :
<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>

simple PHP integer conversion

convert this: $300
to this : 300
can't do it with intval() or (int)
typecasting
if the non-numerical character is
suffixed (300$), both works and
returns 300
if it is prefixed it returns 0
the non-numerical character can be anything other than the "$"(i.e. "askldjflksdjflsd")
Please help
EDIT : list items are not requirements, they are a list of activities and observations I have made. Sorry:(
preg_match('/\d+/', $num, $matches);
echo $matches[0];
You can get rid of all the non-digits in the input by doing:
$input = preg_replace('/\D/','',$input);
$number = filter_var($number, FILTER_SANITIZE_NUMBER_INT);
print (int) trim('$300', '$');
No need for a regex.
$number = (integer) str_replace('$', '', $number);

Categories