Correct the float values - php

I read some data from a csv file. Each line in the file has a float value. these values can be either:
.123 : starting with a period, so I need to add a zero before.
1,23: having a delimter comma ',' instead of period so I need to change that.
1.2e3 having an exponential-format so I need to convert it to decimal format.
I can't use the function number_format because I can't set the number of decimal points (the float numbers don't have a fixed length of the decimal part and we want to take them as they are to not lose data).
Here is what I tried so far; I built two functions, the first one filters the floats, the second one corrects them when the filter returns false:
function validateFloat($float){
if(!filter_var($float,FILTER_VALIDATE_FLOAT,array('flags' => FILTER_FLAG_ALLOW_FRACTION))){
return false;
}
}
function correctFloat($float){
if (validateFloat($float)==false){
$number = number_format($float,null,'.');
str_replace($number,'',$line);
}
}
I don't know how to build the correctFloat function. Any suggestions ? Appreciate it.

Your function can check if there is a comma and get the correct deliminator then use floarval on any other case
function change_format($value){
if(is_string($value)){
//has to be a string if using ','
$value= str_replace(",",".",$value);
}
return floatval($value);
}
echo change_format(.123) ."<br>";
echo change_format("1,23") ."<br>";
echo change_format("1.2e3");
Outputs:
0.123
1.23
1200

Related

Cut .00 from float variable

I wrote this function for cutting two last characters from (float) type variable. I would like that e.g 315.00 becomes 315
function formatFloat($value) {
$integer = number_format($value, 2);
return $integer;
}
But i have failed - function returns 315.00 :D What's wrong guys?
Use the intval function. Here is the documentation for that.
Write you code like this:
function formatFloat($value) {
$integer = intval($value);
return $integer;
}
Or you can directly pass the variable in that:
intval($value);
Then you don't need to make the function.
Like I mentioned in the comments, if you just use intval(), you can get the integer part of it, and effectively remove the decimal. This means that you don't need a function formatFloat() at all, unless you intend on doing anything more inside it.
echo intval(315.00); // 315
If you insist on using number_format(), you should see that according to the documentation, the second parameter displays the amount of decimal places. You have set it to two, so you will get two decimal places. Set it to zero, or remove it altogether (as it's default zero).
echo number_format(315.00); // 315
echo number_format(315.00, 0); // 315
echo number_format(315.00, 2); // 315.00
Live demo
PHP.net on number_format()
PHP.net on intval()

Addition to number formed using number_format() php function

When i try to add a integer to 3 digit number formed using php number_format() function give right result but when number become 4 digit it give wrong output.
I have tried this. please explain me the reason behind this??
$num1=number_format(1000.5,2);
$num1+=1;
echo $num1;
Output:2
But
$num1=number_format(100.5,2);
$num1+=1;
echo $num1."\n";`
Output:101.5
number_format() returns a string not a number. It is there to format a numeric type (integer, float) to a string with a specific, desired "layout". So what you do is add the number 1 to the string resulting from number_format, which will try to cast the string back to a number, apparently resulting in 1 for the string cast as well, which gives you 2 total.
tl;dr; Do calculations on numbers only and then do number_format at the very end to output in a defined format.
$num1 = number_format(1000.5, 2);
var_dump($num1);
// => string(8) "1,000.50"
$num1 += 1;
var_dump($num1);
// => int(2)
Function number_format() returns string.
And that string is type cast to integer when you are adding 1
See Type Juggling
The quickest solution would be using str_replace() on your formatted number.
Something like this would do:
(float)str_replace( ',', '', $formatted_number )
By removing the commas from the string and asking for the float value, you'll get a usable number.

is_double function in a while loop condition

I'm trying to get the fractional number count of a decimal number. I tried following simple code, but the loop runs forever.
$var = 123.456;
$fraction_count = 0;
echo $var, "<br>";
while (is_double($var)) {
$var *= 10;
$fraction_count++;
echo $var, "<br>";
}
I'm new to php so, forgive me if this is a stupid question!
Floating point numbers are not trivial to deal with (see the manual for more information). But you don't even need to deal with the number as such.
If you treat it as a string, you can explode() on the . and use strlen() on the second part to get the $fraction_count:
$var = 123.456;
$parts = explode('.', $var);
$fraction_count = strlen($parts[1]);
Since PHP doesn't save trailing 0s on numbers, this will work for 123.4560 as well, but be sure to input it as a number, "123.4560" will get you a wrong result.

How to manage number values with points?

$val represents 1,949.58 from my sql
$sold = 50;
if ($val>$sold){
echo "true";
}
else
{
echo "false";
}
I get false. somehow 50 is bigger than 1,949.58 and this because of the ',' sign. I need some advices on how to manage this right. Thx
$val is interpreted by php to be a string. When doing the comparison, it's doing a string compare so you aren't going to get the results you expect.
You need to force them to be a floating point type. Look at http://php.net/manual/en/function.floatval.php Specifically the comments on that function.
Something like this should work:
function floatvalue($value) {
return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}
You need to convert these values to floats instead of strings. Right now you're doing string comparisons and not numerical comparisons. The following converts those strings to floating values.
$val = parseFloat('1,949.58'.replace(/\,/g,""))
$sold = parseFloat('50')
The .replace removes the "," from your original string before it's parsed to a Float.

PHP Excel Calculate Formulas

Im trying print Excel file data on a page. To do it i used PHPExcel lib, all works good, beside printing formulas, i have simple example with such formula =SUM(C2:C5)
I print values in a such way:
$val = $cell->getValue();
echo '<td>' . $val . '</td>';
how can i check if $val is a formula?
PHPExcel_Cell_DataType::dataTypeForValue($val); told me that it is a just another one string in my $val
Ofc i can calculate it in a loop, and chek if it`s a last row - insert needed info by hands, but how i can calculate it easy way?
Will be pleased to hear your advice. Thanks.
PHPExcel_Cell_DataType::dataTypeForValue($val); will always tell you string for a formula, because a formula is a string. Being a formula is related to the cell, not the data. The getDataType() method of the cell object will return an 'f' for formula.
If you use getCalculatedValue() rather than getValue(), then PHPExcel will determine whether the cell contains a formula or not. If it does, then it will calculate the result and return that, otherwise it will simply return whatever would have been returned by getValue(); The other method you might consider is getFormattedValue() which will return a string, formatted according to whatever rules are set for the cell. And if it was a formula cell, then it will have done the calculation as well. Particularly useful to get a date string rather than a numeric value from cells formatted as dates.
You can also avoid looping of the cells by using the toArray() or rangeToArray() methods, which will return an array of cell values, though you'd still need to loop the array. Both of these methods have arguments allowing you to set whether formulae should be calculated, and whether formatting should be applied.
"how can i check if $val is a formula?"
Every formula in excel start with = so :
<?php
$String = 'SUM(B3:B8)';
# See http://www.php.net/manual/en/language.types.string.php
# $String{} is deprecated as of PHP 6.
if($String[0] == '='){
echo 'Yes';
} else {
echo 'No';
}
?>
OR
<?php
function IsExcelFormula($String=null){
if(!$String OR strlen($String) <= 0){
return false;
}
$First = $String[0];
return ($First == '=' ? true : false);
}
var_dump(IsExcelFormula('=SUM(B8:B9)')); // bool(true)
var_dump(IsExcelFormula('TOTAL(B3:B6)')); // bool(false)
?>

Categories