1

I am trying to get only integer from string for these i am using filter_var in php

Here is my code

$str="Your base price is 456";
echo filter_var($str,FILTER_SANITIZE_NUMBER_INT); 

But if the string contains a floating point value filter_var returns integer without the floating point value.

Eg; 
$str="Your base price is 45.57";
echo filter_var(currencyConvert($currency,$results[0]->base_price),FILTER_SANITIZE_NUMBER_INT); 

this will echo integer as 4557 but i need the value as same as the string.

ie it should be 45.57 but i will get it as 4557

Is any way to get this as correct float value?

3
  • What exactly is your objective? Do you want to print it as a floating point value? Or an integer? Commented Mar 31, 2016 at 6:49
  • Print as a floating point value Commented Mar 31, 2016 at 6:51
  • Have you tried FILTER_SANITIZE_NUMBER_FLOAT? Generally, it is not advisable to use INT functions on non-integers, and this is one of many such cases. Commented Mar 31, 2016 at 6:52

5 Answers 5

2

Try using FILTER_SANITIZE_NUMBER_FLOAT but you must use the correct flag ie FILTER_FLAG_ALLOW_FRACTION

$str="Your base price is 45.57";
echo filter_var($str,FILTER_SANITIZE_NUMBER_INT);
print_r("\n");
echo filter_var($str,FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
print_r("\n");

This prints

4557
45.57
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

$str = "Your base price is 456";
echo preg_replace("/[^0-9\.]/", '', $str);  // Prints 456
echo "<br/>";
$str = "Your base price is 45.57";
echo preg_replace("/[^0-9\.]/", '', $str);  // Prints 45.57

Hope this helps.

Comments

0

In this line of code:

echo filter_var($str,FILTER_SANITIZE_NUMBER_INT); you have used FILTER_SANITIZE_NUMBER_INT to get integer number form a string. To get float number from a string you can use FILTER_VALIDATE_FLOAT. For more information check it out here: http://www.w3schools.com/php/filter_validate_float.asp

Comments

0

Use below code it will help you.

$str="Your base price is 45.6";
preg_match_all('!\d+(?:\.\d+)?!', $str, $matches);
$floats = array_map('floatval', $matches[0]);
print_r($floats);

Or

echo filter_var($str,FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

1 Comment

Use any above code it will surly solved your problem. @Blessan Kurien
0

Try This:

$str = "Your base price is 45.57";
$float_val=(float) filter_var( $str, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ) ;
echo $float_val;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.