i have input form currency with format like this 1,000.00
and i want to save in database in decimal format like 1000.00
how to change it in controller, when save it it will automatically change to decimal format?
$num = '3,500.20';
$formattedNum = number_format($num, 3, '', '');
echo $formattedNum;
the code above convert to 3000 not 3500.20
you can use str_replace of php to get you result:
<?php
$num = '3,500.20';
$formattedNum = str_replace(',', '', $num);
echo $formattedNum;
?>
str_replace funcation replace your ',' with '' a blank value,
To read more about str_replace you can read here
You can just remove comma with str_replace(',', '', $num) for example.
But better to get correct value right from your input.
Input format shouldn't affect actual input value which is 3500.20, that doesn't look as good practice.
Also number_format is not for converting string to numbers, on the contrary it makes pretty string from number(integer/float).
You can try str_replace for the desired result:-
$number = '3,500.20';
$number = str_replace(',', '', $number);
echo $number;
Output
3500.20
Related
I have a string with numbers, stored in $numbers:
3,6,86,34,43,52
What's the easiest way to get the last value after the last comma? In this case the number 52 would be the last value, which I would like to store in a variable.
The number can vary in size, so trying:
substr($numbers, -X)
does not help me out I think.
This should work for you:
Just use strrpos() to get the position of the last comma and then use substr() to get the string after the last comma, e.g.
$str = "3,6,86,34,43,52";
echo substr($str, strrpos($str, ",") + 1);
output:
52
Just explode the string by the separator character and pick the last of the resulting tokens:
<?php
$string = '3,6,86,34,43,52';
$tokens = explode(',', $string);
echo end($tokens);
An alternative would be to use a regular expression:
<?php
$string = '3,6,86,34,43,52';
preg_match('/,([0-9]+)$/', $string, $tokens);
echo end($tokens);
Personally I have the opinion that efficiency is less important that easy of reading and understanding the code these days. Computation power is cheap, developers are expensive. That is why I would use the first approach, expect when the number of elements in the string gets big.
You can do it like this:
$numbers = "3,6,86,34,43,52";
$arr = explode(",",$numbers);
echo $arr[count($arr)-1];
I'd just explode it to an array, and get the last element:
$numbers = '3,6,86,34,43,52';
$arr = explode(',', $numbers);
echo $arr[count($arr) - 1];
A direct, single-function approach would be to trim every upto the last comma.
Code: (Demo)
$numbers = "3,6,86,34,43,52";
echo preg_replace('/.*,/', '', $numbers);
// 52
I have few strings where i need to extract only the prices in php (which will obviously be numerals).
The use cases are follows:
1) Rs. 23,459.45 desired output = 23459.45
2)Our best price 23,459.45 desired output = 23459.45
etc.
I gave the above use cases to give an idea that the preceding characters could be anything.
Please help!
How about:
$arr = array(
'Rs. 23,459.45 ',
'Our best price 23,459.45 ',
);
foreach($arr as $string) {
$string = preg_replace('/^.*?(\d+),?(\d{3})(\.\d{2})?.*$/', "$1$2$3", $string);
echo $string,"\n";
}
output:
23459.45
23459.45
It's:
$result = preg_replace('/[^0-9.]/', '', $string);
-but note, this will not validate numbers or provide valid result in common case since string could contain something like 'foo . bar,baz . price 20.5 with .6 discount' - end result will be not a valid number. So code above answers the question about "how to replace", but does not fit validating a number (and you've not mentioned if that is your goal).
About validating a number - such question will be ambiguous because it's not obvious how to convert ..20.5.6 (which will be result for string above). But if you need only to check that, use is_numeric() on $result, like this:
$string = 'foo . bar,baz . price 20.5 with .6 discount';
$result = preg_replace('/[^0-9.]/', '', $string);
$result = is_numeric($result)?(float)$result:null;
You can use this to validate the above strings. When this function valiadates Rs. , it will return two dots, so I used ltrim to remove the first dot.
<?php
//$s = "Rs. 23,459.45";
$s= "Our best price 23,459.45";
echo $result = ltrim(preg_replace("/[^0-9.]+/", "", $s),'.');
?>
http://codepad.org/cyH5OWyE
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
I am trying to find a piece of regex to remove a currency format.
I have two types of currency values. One is in USD format like 1,000.00 and other is in EUR like 1.000,00. I need to save the value in to db by removing both comma and dot like 1000.00
For example if the user enter the value in USD like 2,222.65, it need to replace to 2222.65,
if the user enter the value in EUR like 2.222,65 it also need to replace to 2222.65,
Instead of complex regex, use NumberFormatter::parse available for PHP 5 >= 5.3.0, PECL intl >= 1.0.0.
// German format
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."<br>\n";
// USD format
$fmt = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
$num = "9,876,543.012";
echo $fmt->parse($num)."<br>\n";
OUTPUT:
1234567.891
9876543.012
One soultion to match what separator in use, and change it to the one you prefere
<?php
/* split input in 3 parts: integer, separator, decimals */
if(preg_match('#^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$#', $input, $matches))
{
/* clean integer and append decimals with your own separator */
$number = ((int) preg_replace('#[^0-9]+#', '', $matches['integer']) . '.' . $matches['decimals']
}
else
{
$number = (int) preg_replace('#[^0-9]+#', '', $input);
}
?>
Notice: I prefer to have my regexp in # insted of /, as i ofen use / inside my regexp,
if ypu prefer / you can use /[^0-9]+/ and /^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$/
This assumes that they all have decimals, but it is the cleanest.
$str = "2,222.65";
$clean = preg_replace('/[^\d]/', '', $str);
$clean = substr($clean, 0,-2) . "." . substr($clean,-2);
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);