PHP: Dividing/Multiplying/Rounding, not exact number - php

I made a survey page and there I'm reading the number of votes from a DB.
Now I wanted to get the percentage of votes for displaying a "progress bar".
I wrote this funcion to get the percentage:
function progress($cur, $max, $round=1) {
return ($max!=0) ? round(($cur/$max) *100, $round).'%' : '0%';
}
This seemed to be working fine, but for some numbers it adds many zeros and a 1 to the correct value.
For example: 3/34 -> 8.800000000000001%. For other values (tested, 1,2,4,6) it's working correctly.
How can I correct this to display 8.8%?

Use the sprintf function in PHP:
$formattedOutput = sprintf("%.1f",$floatValue);
gives you the the $floatValue with one decimal.
see PHP manual for sprintf

Related

Find list of words(comma separated number) that are present in text based column in mysql database

I am using php/mysql.
I am storing comma separated 6 digit numbers in text based column of table in database.
I want to get the method to find which numbers in given range are present in my database.
My table looks like :
|id|date|commaSeperatedList|
Now as input to sql I want to give a range of number (e.g 234101-234200).
Therefore I am expecting output to be in form of :
|id|date|number|
So, far the solution I have worked on is : Use of PHP's range function.
Using that I created a string based Long Where Clause.
foreach( $words as $word) {
$word=str_pad($word, 6, '0', STR_PAD_LEFT);
$whereClause .= ' commaSeperatedList LIKE "%' . $word . '%" OR';
}
Problem with it is that : I dont get to know exactly which were the numbers that were found common .
e.g lets say List has :
109001,234122,234123,345650
I am giving the range (234101-234200)
The above statement finds all rows that contain any number in provided range . However I also want to know which exact numbers were matched. In my provided example these numbers are : 234122,234123
So, expected output should be :
|1|date|234122|
|1|date|234123|
Any help in this regard will be appreciated.
Eventually had to store data by normalization.
There are queries(Full Text Match) that were doing the work but not only they were complex but slow as well.
As for me , Its always better to store data properly in normalized format. (Its not a space/time tradeOFF).
For others in similar situation . Do some extra work on data and store it properly.
Thanks everyone for valuable answers !
Try This Code May Help You to find between range
<?php
$list = "109001,234122,234123,345650";
$from = "234101";
$to = "234200";
$list = explode(",",$list);
foreach($list as $val)
{
if($val > $from && $val < $to)
{
echo $val."<br>";
}
}
?>

Issue Scraping with PHP

I am trying to attain a value, but step over other values that change dynamically.
The table section looks as follows:
Total 1.18 3.33 $20,000 16.2%
The code I am using to find the third value in preg_match is:
<?php
function get_total(){
$file_string = file_get_contents('url');
preg_match('#Total</td><td>\d\.\d+</td><td>d\.\d+</td><td>$(\d+)</td><td>d+\.\d\%\</td></tr></table><br><span id="ExStockDetailTableF1F2"#',$file_string, $data);
$loss = $data[1];
return $loss;
}
?>
Wouldn't it be easier just search for \$[\d\,]+ since represent third group?

PHP and MYSQL AJAX - autofill multiple text fields

I am using the great tutorial provided by Nodstrum. I am attempting to autofill multiple text fields with PHP, MYSQL, and AJAX. I have a PHP script, here is the line of code returning my results:
echo '<li onClick="fill(\''.$result->name.'|'.$result->id.'\');">'.$result->name.'</li>';
Notice that I am seperating my results with a pipestem character.
Here is the function where I am receiving the error 'Undefined or not an object' I am breaking out the values and using the pipestem as splitting the values from mysql.
function fill(thisValue) {
myvalues=thisValue.split('|') {
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
}
window.setTimeout("$('#suggestions').hide();", 200);
}
If I 'ok' the error messages, I will eventually see both values displayed in the text fields, so I believe I am retreiving the values properly from MySQL. I appreciate any help anyone can provide to get me steered in the right direction, or a fresh perspective.
Thanks Again,
--Matt
The value you are passing that becomes thisValue is null or undefined. You can test this parameter before blindly trying to .split it (the split function works only on strings).
function fill(thisValue) {
// "value" will always be a string
var value = thisValue ? String(thisValue) : '';
// this line will not generate an error now
var myvalues=value.split('|');
// but these ones might! make sure the length of myvalues is at least 2
if (myvalues.length >= 2) {
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
}
// this might need to go inside the above if
window.setTimeout("$('#suggestions').hide();", 200);
}
Try this:
function fill(thisValue) {
myvalues=thisValue.split('|');
$('#inputString').val(myvalues[0]);
$('#email').val(myvalues[1]);
window.setTimeout("$('#suggestions').hide();", 200);
}

PHP GET number query

Hi to all!
I have a query that gets the name and an id.
The results is like this :
54 - Rian Ree Barrientos
I wanted to get the number 54.
I used echo (int)$_GET['number'];
But the result is "0". How can I get the number?
You can't get it that way, you need to make two query string vars for it eg:
<a href="somepage.php?number=54&str=some_string">
Make sure that if you do so, you use the urlencode function.
Now you can use:
echo (int) $_GET['number'];
And:
echo $_GET['str'];
Otherise you can use the explode function to get the two values by specifying the - delimiter.
I think you want id from the value you get from the query
I think you want something like following
$strPrice1 = mysql_query("SELECT id, name FROM table_name where id=".$_GET['id'] );
$strPrice = mysql_fetch_array($strPrice1);
echo (int)$_strPrice['id'];
But the result is "0". How can I get the number?
Really?
When I run:
print (int)('54 - Rian Ree Barrientos') . "\n";
I get 54
(php v 5.1.6)
Maybe $_GET['number'] doesn't contain what you think.
C.

Prettifying a conversion from m(metres) to feet(') and inches ('')

I'm creating table for defining an individual's BMI. The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches.
In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't laugh...) the following:
<?php
$m; // height in m
$hInInches = ($m*3.2808399)*12;
$hInImp = explode(".",$hInInches);
$hInFt = $hInImp[0];
$hInInches = substr(12*$hInImp[1],0,2);
?>
I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate x numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...
Here is an approach, in psuedo-code:
inches_per_meter = 39.3700787
inches_total = round(meters * inches_per_meter) /* round to integer */
feet = inches_total / 12 /* assumes division truncates result; if not use floor() */
inches = inches_total % 12 /* modulus */
You could pull out the 12 to a constant as well...
To me you should avoid the string manipulation functions as derobert already stated.
In php the code should be similar to the following one:
<?php
$m=2; // height in m
$hInFeet= $m*3.2808399;
$hFeet=(int)$hInFeet; // truncate the float to an integer
$hInches=round(($hInFeet-$hFeet)*12);
?>
Just two multiply and a subtraction (plus a function call to round) are quite economic, and the code is quite readable too.
i'm not sure if you consider this prettier; however, I'd argue that an ajax/javascript solution might be idea. As the user enters the value, the results update.
with regards to your code
* define M_TO_FEET, FEET_TO_INCH constants.
* define 2 equations feet_to_metres(value_to_convert) and metres_to_feet(value_to_convert)
* write the conversion code in each and let it return the result
and then you can create a simple if statement:
* If user inputs metres, then metres_to_feet(value_entered_by_user)
<?php echo metersToFeetInches(3); //call function ?>
<?php
function metersToFeetInches($meters, $echo = true)
{
$m = $meters;
$valInFeet = $m*3.2808399;
$valFeet = (int)$valInFeet;
$valInches = round(($valInFeet-$valFeet)*12);
$data = $valFeet."′".$valInches."″";
if($echo == true)
{
return $data;
} else {
return $data;
}
}
?>
output : 9′10″

Categories