Change comma to dot, working with decimals in php - php

So i have some fields coming from the form. Here you can type 0.3 and it will insert 0.3 in to the database. Do you type 0,3 it will just insert "0".
$product['protein']; // 0,3
So to this above how can i replace a comma with a dot ?

Try PHP's function str_replace():
$product['protein'] = str_replace(',', '.', $product['protein']);
Which should be a good fit.
You could think to use number_format():
number_format($value, $numberOfDecimals, $charaForDecimalPoint, $charForThousandsSeparator)
but in your case it wouldn't apply, due to the fact that your starting value ("0,3") wouldn't be recognized as a number.
In fact, the decimal point for a numeric value must be a dot(".").
Use number_format only if your starting value is a true number.

$product['protein'] = str_replace(",",".",$product['protein'])
For more info on the str_replace function visit: http://uk.php.net/str_replace

try
$product['protein'] = str_replace(",",".",$product['protein'])

$product['protein'] = str_replace(',', '.', str_replace('.', '', $product['protein']));

Related

Big numbers regex

$value = preg_replace("/[^0-9]+/", '', $value);
How could I edit this regex to get rid of everything after the decimal point? There may or may not be a decimal point.
Currently "100.1" becomes 1001 but it should be 100.
Complete function:
function intfix($value)
{
$value = preg_replace("/[^0-9]+/", '', $value);
$value = trim($value);
return $value + 0;
}
It is used to format user input for numbers as well as servers output to format numbers for the DB. The functions deals with very large numbers, so I can't use intval or similar. Any extra comments to improve this function are welcome.
You could just change the regex to /[^0-9].*/s.
.* matches zero or more characters, so the first character that is not a digit, and the digits that immediately follow, would be deleted.
You need to have a pattern that starts the search with a decimal place. At the moment you're only deleting the . not the numbers after it... So you could do '/\.[\d]+/'
$text = "1201.21 12 .12 12.21";
$text = preg_replace('/\.[\d]+/', '' ,$text);
The above code would result in $text = "1201 12 12"
Why not $value = round($value, 0);? This can handle large values and is meant to get rid of the following decimals mathematically (I'd rather work with numbers as numbers not as strings). You can pass PHP_ROUND_HALF_DOWN as a third parameter if you want to just get rid of the decimals 10.7 -> 10. Or floor($value); could work too.

PHP - floatval cuts of position after decimal point?

I have this PHP code:
<?php
$float = "1,99";
echo "<p>$float<br>";
$float = floatval($float); // Without this line number_format throws a notice "A non well formed numeric value encountered" / (float) $float leads to the same output
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>
Why does it return 1? Don't get that.
And: yes, there is a sense in converting 1,99 to 1,99 ;-)
Thanks for advise...
The problem is, that PHP does not recognize the , in 1,99 as a decimal separator. The float type is defined as having the following formal definition:
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
That means it'll only accept . as a decimal separator. That's in fact the same reason why number_format throws a warning on an invalid datatype because it cannot convert 1,99 to a float internally.
The following should work:
$float = "1,99";
echo "<p>$float<br>";
$val = number_format(str_replace(',', '.', $float), 2,'.', ',');
echo "$float</p>";
floatval recognizes the comma (,) as a character and not as a number, so it cuts off everything that comes after it. In this case, that's the 99. Please use a dot (.) instead of a comma (,) and it will probably work.
Example floatval (source: http://php.net/manual/en/function.floatval.php):
<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>
1,99 is not a valid php float. The issue is your comma (,). In PHP you have to use dot (.) as floating point separator.
<?php
$float = "1.99";
echo "<p>$float<br>";
$float = (float)$float;
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>

php preg_match_all results from (numerical) STRING to DECIMAL - type

I have script that identifies with preg_match_all some numbers from a given file and in a given format '#(\d\,\d\d\d\d)#' (decimal, with 4 decimals). With them, later, I need to do some math operations to find out the sum, average etc.
With print_r I can see all matches from the array and it is ok (4,3456, 4,9098, etc.). I verify the type of variables and gettype() returned string
Unfortunately I cannot do math operations with them because when I use the variables in a math expression the result is always rounded regardless of what came afer the comma.
For example:
4,3456 + 4,9098 + 4,3456 = 12, or 12,0000 -- if I use number_format.
I used . instead of , in the numbers, I formatted the results with number_format, but have had no success. It seems I am missing something.
Thanks for help!
The error happens even before the number_format call -- PHP considers . as the decimal separator, not ,. you need to str_replace all your array elements:
$values_array = str_replace(",", ".", $values_array)
PHP uses the . character as decimal separator, so you have to replace the , by a . in your matched numbers before converting them to numbers:
$number = floatval(strtr("1,234", ",", "."));
// 1.234
Example:
<?php
$numbers = array("1,234", "5,67");
$numbers = str_replace(",", ".", $numbers);
echo number_format($numbers[0] + $numbers[1], 4, ',', ' ');
Try it here: http://codepad.org/LeeTiKPF

Decimal number with comma instead of point (php and sql)

I'm doing a little application of adding prices and decimals. Points are normal to use with decimals, but how can I write decimal number with comma as input (543,35 instead of 543.35) and then maybe change it with point to the database (mysql)? Then print it back form the database with the comma. Reason is that comma (,) is more used in Finland than point (.) when write decimal numbers.
Thank you very much!
Samuel
$input = '5,50';
$output = str_replace(',', '.', $input);
var_dump($output); // string(4) "5.50"
$number = (float)$output;
var_dump($number); // float(5.5)
you need not do anything in the sql end. you want to format the decimal value in php (this assumes php4/php5): Set the third parameter $dec_point to ','
// string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )
<?php
$number = 1234.56;
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
source:
http://php.net/manual/en/function.number-format.php
Cheers!
the PHP number_format function is what you need :
number_format(5.50, 2, ',');
...should do the trick.
As it's been said, it's best to save the value as a float and then format for display. As an alternative to the previously suggested number_format(), you could try money_format() http://us.php.net/manual/en/function.money-format.php It doesn't work in a windows environment though if that is important to you.
No, using comma as a decimal separator for arithmetic operations is not supported. Filter your input and replace the comma with a period, then format your output as you wish.

How to get rid of extra elements in string literal in php?

I have number like 9843324+ and now I want to get rid of + at the end and only have 9843324 and so how should I do this in php ?
Right now I am doing $customer_id = explode('+',$o_household->getInternalId); also $o_household->getInternalId returns me 9843324+ but I want 9843324, how can I achieve this ?
Thanks.
if you just want to pop the + off the end, use substr.
$customer_id = substr($o_household->getInternalId, 0, -1);
or rtrim
$customer_id = rtrim($o_household->getInternalId, "+");
You can use a regeular expression to remove anything that isn't a number
$newstr = preg_replace("/[^0-9]+/","",$str);
$customer_id = rtrim ( $o_household->getInternalId, '+' );
rtrim function reference
rtrim removes the characters in the second argument (+ only in this case) from the end of a string.
In case there is no + at the end of the string, this won't mess up your value like substr.
This solution is obviously more readable and faster than, let's say preg_replace too.
you could use intval($o_household->getInternalId)
Is there a reason you need to use explode? i would just use substr as Andy suggest or str_replace. Either would work for the example you provided.
You can use intval to get the integer value of a variable, if possible:
echo intval($str);
Be aware that intval will return 0 on failure.

Categories