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>";
?>
Related
In my store i am trying to change a String into an integer the code which I am using is:
<?php echo $_excl; ?>
<?php $int_excl = intval($_excl);?>
<?php var_dump ($int_excl);?>
When i var_dump $int_excl is says the value is 0 when it should be 4.99 .
What am I doing wrong?
var_dump ($_excl) returns string(33) "£4.99"
Both floatval and intval methods start to look for numbers from the beginning of the string (removing the preceding whitespace) - and stop looking at the first symbol that cannot be a part of the number. In your case, it's the very first one - £. That's why intval just returns 0 (as floatval does).
One way to resolve this is to remove all the non-digit symbols at the beginning of your string with preg_replace:
$excl = '£4.99';
$value = preg_replace('/^\D+/u', '', $excl);
var_dump(intval($value)); // int(4)
var_dump(floatval($value)); // float(4.99)
Demo. This approach is change-resistant - it works (without any modifications) if £ is replaced with $ or any other currency symbol, or dropped altogether.
<?php
$_excl = '4.99' ;//assuming
echo $_excl;
$int_excl = floatval($_excl);
var_dump ($int_excl);
?>
Use above code, since $_excl = 4.99 which is a float value, intval() would return 4.
This should work for you:
(You have to remove the character £ from the string)
<?php
$_excl = "£4.99";
$_excl = str_replace("£", "", $_excl);
$int_excl = floatval($_excl);
var_dump ($int_excl);
?>
Output:
float(4.99)
You are parsing float values, and therefore need floatval() PHP Float Manual.
If intval() returns 0, it means that the conversion failed. Source: PHP Intval)
In your case, the conversion fails because the string doesn't start with a number, but with a currency symbol.
This should solve your problem:
<?php
echo $_excl;
$int_excl = floatval(ltrim($_excl, '£'));
var_dump ($int_excl);
?>
(ltrim removes the first character if it is £)
I have a STRING $special which is formatted like £130.00 and is also an ex TAX(VAT) price.
I need to strip the first char so i can run some simple addition.
$str= substr($special, 1, 0); // Strip first char '£'
echo $str ; // Echo Value to check its worked
$endPrice = (0.20*$str)+$str ; // Work out VAT
I don't receive any value when i echo on the second line ? Also would i then need to convert the string to an integer in order to run the addition ?
Thanks
Matt
+++ UPDATE
Thanks for your help with this, I took your code and added some of my own, There are more than likely nicer ways to do this but it works :) I found out that if the price was below 1000 would look like £130.00 if the price was a larger value it would include a break. ie £1,400.22.
$str = str_replace('£', '', $price);
$str2 = str_replace(',', '', $str);
$vatprice = (0.2 * $str2) + $str2;
$display_vat_price = sprintf('%0.2f', $vatprice);
echo "£";
echo $display_vat_price ;
echo " (Inc VAT)";
Thanks again, Matt
You cannot use substr the way you are using it currently. This is because you are trying to remove the £ char, which is a two-byte unicode character, but substr() isn't unicode safe. You can either use $str = substr($string, 2), or, better, str_replace() like this:
$string = '£130.00';
$str = str_replace('£', '', $string);
echo (0.2 * $str) + $str; // 156
Original answer
I'll keep this version as it still can give some insight. The answer would be OK if £ wouldn't be a 2byte unicode character. Knowing this, you can still use it but you need to start the sub-string at offset 2 instead of 1.
Your usage of substr is wrong. It should be:
$str = substr($special, 1);
Check the documentation the third param would be the length of the sub-string. You passed 0, therefore you got an empty string. If you omit the third param it will return the sub-string starting from the index given in the first param until the end of the original string.
$databtcguild = file_get_contents('http://btcguild.com');
preg_match('~<b>Pool Speed</b></a> (.*?) TH/s~',$databtcguild,$btcguild);
$btcguildhashrategh = ($btcguild[1] * 1000);
echo $btcguildhashrategh;
echo "<br>";
echo $btcguild[1];
For some reason this code is outputting the wrong answer. For example, $btcguild[1] will equal 12,747 and this code will output 12000. I'm completely lost here. Thanks for any help.
The "hash speed" value you are extracting from that site has a value with a comma in it:
12,747
PHP needs to convert this string to a numeric value, and the comma causes the numeric value 12 to be returned (, is interpreted as a decimal)
Make sure you strip all non-numeric characters before multiplying:
//keep only values 0-9 and decimal (period)
$hash_speed = preg_replace("/[^0-9.]/", "", $btcguild[1]);
$btcguildhashrategh = ($hash_speed * 1000); //returns 12747000
Try explicitly type-casting the result: $btcguildhashrategh = ((double)$btcguild[1] * 1000);
Otherwise PHP will convert it into an int.
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']));
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.