How do I output a value as a number in php? I suspect I have a php value but it is outputting as text and not as a number.
Thanks
Here is the code - Updated for David from question below
<?php
if (preg_match('/\-(\d+)\.asp$/', $pagename1, $a))
{
$pageNumber = $a[1];}
else
{ // failed to match number from URL}
}
?>
If I call it in: This code it does not seem to work.
$maxRows_rs_datareviews = 10;
$pageNum_rs_datareviews = $pagename1; <<<<<------ This is where I want to use it.
if (isset($_GET['pageNum_rs_datareviews'])) {
$pageNum_rs_datareviews = $_GET['pageNum_rs_datareviews'];
}
If I make page name a static number like 3 the code works, if I use $pagename1 it does not, this gives me the idea $pagename1 is not seen as a number?
My stupidity!!!! - I used $pagename1 instead of pageNumber
What kind of number? An integer, decimal, float, something else?
Probably the easiest method is to use printf(), eg
printf('The number %d is an integer', $number);
printf('The number %0.2f has two decimal places', $number);
This might be blindingly obvious but it looks like you want to use
$pageNum_rs_datareviews = $pageNumber;
and not
$pageNum_rs_datareviews = $pagename1;
echo (int)$number; // integer 123
echo (float)$number; // float 123.45
would be the easiest
I prefer to use number_format:
echo number_format(56.30124355436,2).'%'; // 56.30%
echo number_format(56.30124355436,0).'%'; // 56%
$num = 5;
echo $num;
Any output is text, since it's output. It doesn't matter what the type of what you're outputting is, since the human eye will see it as text. It's how you actually treat is in the code is what matters.
Converting (casting) a string to a number is different. You can do stuff like:
$num = (int) $string;
$num = intval($string);
Googling php string to number should give you a beautiful array of choices.
Edit: To scrape a number from something, you can use preg_match('/\d+/', $string, $number). $number will now contain all numbers in $string.
Related
I am working with huge numbers for website purposes and I need long calculation. When I echo a long number I don't get the correct output.
Example
// A random number
$x = 100000000000000000000000000;
$x = number_format($x);
echo "The number is: $x <br>";
// Result: 100,000,000,000,000,004,764,729,344
// I'm not getting the value assigned to $x
Your number is actually too big for php standard integers. php uses 64 bit integers which can hold values within range -9223372036854775808 (PHP_INT_MIN)
to +9223372036854775807 (PHP_INT_MAX).
Your number is about 87 bits long which simply is too much.
If you really need such big numbers you should use the php BC math types, explained in the manual: http://php.net/manual/en/ref.bc.php
If you just want to format a string formed like a huge number then use something like this:
function number_format_string($number) {
return strrev(implode(',', str_split(strrev($number), 3)));
}
$x = '100000000000000000000000000';
$x = number_format_string($x);
echo "The number is: $x\n";
// Output: The number is: 100,000,000,000,000,000,000,000,000
Edit:
Added strrev() to function because the string needs to be reversed before splitting it up (thanks to #ceeee for the hint). This ensures that the delimiter is placed at right position when length of input is not divisible by 3. Generated string needs to be reversed afterwards again.
Working example can be found at http://sandbox.onlinephpfunctions.com/code/c10fc9b9e2c65a27710fb6be3a0202ad492e3e9a
answer #maxhb has bug. if the input is '10000000000000000000000' the out put would be:
The number is: 100,000,000,000,000,000,000,00
Which is incorrect. So try below code:
function number_format_string($number, $delimeter = ',')
{
return strrev(implode($delimeter, str_split(strrev($number), 3)));
}
$x = '10000000000000000000000';
$x = number_format_string($x);
echo "The number is: $x\n";
// Output: The number is: 10,000,000,000,000,000,000,000
The largest integer that can be represented in a 64bit PHP install, compared to your number:
9,223,372,036,854,775,808 - largest possible signed 64bit integer
100000000000000000000000000 - your number
since you're exceeding the maximum number size, you can't expect to get useful results without using something like gmp/bcmath.
PHP does not yet support formatting long numbers, even when you always keep them as strings in your code (to avoid issues with PHP’s int type):
php > echo number_format('100000000000000000000000000');
100,000,000,000,000,004,764,729,344
php > echo number_format('3.14159265358979323846', 20);
3.14159265358979311600
The underlying ICU library supports formatting arbitrary precision decimal numbers, but PHP doesn’t use the relevant function yet – see request #76093.
http://php.net/manual/en/function.number-format.php
That is the solution:
<?php
# Output easy-to-read numbers
# by james at bandit.co.nz
function bd_nice_number($n) {
// first strip any formatting;
$n = (0+str_replace(",","",$n));
// is this a number?
if(!is_numeric($n)) return false;
// now filter it;
if($n>1000000000000) return round(($n/1000000000000),1).' trillion';
else if($n>1000000000) return round(($n/1000000000),1).' billion';
else if($n>1000000) return round(($n/1000000),1).' million';
else if($n>1000) return round(($n/1000),1).' thousand';
return number_format($n);
}
?>
I am trying to create an ecommerce store and our prices need to fluctuate with the exchange rate for different countries so I'm dealing with a lot of decimal places.
What I want to do is round the original price to the nearest full number (as in they can keep the change). But then I want to format that as a currency with two decimal places.
<?php
$number = 12345.6789;
echo $number; // outputs '12345.6789'
$number = number_format($number,0);
echo $number; // outputs '12,346'
$number = number_format($number,2);
echo $number; // outputs '12.00'
?>
After formatting to no decimal places it starts reading the ',' as the decimal separator instead of the thousands separator and formats that for two decimal places.
It also gives the following error:
A non well formed numeric value encountered in C:\wamp64\www\Lifting365\test.php on line 6
How can I achieve what I am looking for?
As specified in the documentation, number_format returns a string value, you can't reuse it as a number.
Use the function round() to round your number, if you want to round it to the direct upper integer use ceil() instead.
number_format(round(12345.6789), 2);
// apply intval to get the low integer value (for change purposes)
$number = 12345.6789;
echo $number; // outputs '12345.6789'
echo intval($number)."<br/>"; // outputs '12345'
echo number_format(intval($number),0,'.','.'); // outputs '12.345'
echo number_format(intval($number),0,'.',','); // outputs '12,345'
Use round function and then number_format.
// returns 12,346.00
number_format(round(12345.6789), 2);
The function number_format accepts 4 parameters. Per default a point will be used as decimal seperator and comma as thousands seperator (12345.6789 become 12,346 after your first call; as excepted). It's not explicitly documented but number_format also rounds.
http://php.net/manual/de/function.number-format.php
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
You are getting an error because you reuse the same variable $number. After your first call to number_format you dont have a float value anymore.
<?php
$number = 12345.6789;
echo $number."<br>"; // outputs 12345.6789
echo number_format($number,0)."<br>"; // outputs 12,346
echo number_format($number,2)."<br>"; // outputs 12,345.68
?>
If you are not sure what is in your variable you can apply floatval to it.
echo number_format(floatval($number),2);
The PHP function that you're looking for is money_format() http://php.net/manual/en/function.money-format.php have a good read through the manual page (including the comments)
Hi i need to save a 010 number in $number and if i do like this php will remove the starting 0
$number = 010
And echo of this will return 10 how can i make it not to remove the initial 0
BR
Martin
Use it as a String:
$number = '010';
Use str_pad() function.
echo str_pad('10',3,'0',STR_PAD_LEFT)
http://php.net/manual/en/function.str-pad.php
Do remember that numbers starting with 0 can also be treated as octal number notation by the PHP compiler, hence if you want to work with decimal numbers, simply use:
$num = '010';
This way the number is saved, can be stored in the database and manipulated like any other number. (Thx to the fact that PHP is very loosely typed language.)
Another method to use would be:
Save number as $num = 10;
Later while printing the value you can use sprintf, like:
sprintf("%03d", $i);
This will print your number in 3 digit format, hence 0 will be added automatically.
Another method:
<?php
$num = 10;
$zerofill = 3;
echo str_pad($num, $zerofill, "0", STR_PAD_LEFT);
/* Returns the wanted result of '010' */
?>
You can have a look at the various options available to you and make a decision. Each of the method given above will give you a correct output.
If I have, say, 8.1 saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1.)
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
DEMO.
If you're dealing with whole numbers (as you said), you could use the intval function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.is-int.php
Convert a string to a double - is this possible?
get this from my database:
252.587254564
Well i wanna remove the .587254564 and keep the 252, how can i do that?
What function should i use and can you show me an example?
Greetings
You can do it in PHP:
round($val, 0);
or in your MYSQL statement:
select round(foo_value, 0) value from foo
You can do a simply cast to int.
$var = 252.587254564;
$var = (int)$var; // 252
As Tricker mentioned you can round the value down or you can just cast it to int like so:
$variable = 252.587254564; // this is of type double
$variable = (int)$variable; // this will cast the type from double to int causing it to strip the floating point.
In PHP you would use:
$value = floor($value);
floor: Returns the next lowest integer value by rounding the value down if necessary.
If you wanted to round up it would be:
$value = ceil($value);
ceil: Returns the next highest integer value by rounding the value up if necessary.
You can just cast it to an int:
$new = (int)$old;
Convert the float number to string, and use intval to convert it to integer will give you 1990
intval(("19.90"*100).'')
Before using above answer what is your exact requirement please see bellow example output.
$val = 252.587254564;
echo (int)$val; //252
echo round($val, 0); //253
echo ceil($val); //253
$val = 1234567890123456789.512345;
echo (int)$val; //1234567890123456768
echo round($val, 0);//1.2345678901235E+18
echo ceil($val); //1.2345678901235E+18
$val = 123456789012345678912.512345;
echo (int)$val; //-5670419503621177344
echo round($val, 0);//1.2345678901235E+20
echo ceil($val); //1.2345678901235E+20
you can use echo (int) 252.587254564;
positive number:
round(252.587254564) // 253
floor(252.587254564) // 252
ceil(252.587254564) //252
(int)252.587254564 // 252
intval(252.587254564) // 252
~~252.587254564 // 252
negative number:
round(-252.587254564) // -253
floor(-252.587254564) // -253
ceil(-252.587254564) // -252
(int)-252.587254564 // -252
intval(-252.587254564) // -252
~~-252.587254564 // -252
if you want just remove decimals without round you can use one of above codes except round and floor(for negative number).
But I recommended the last one, it's simpler and faster using prefix ~~
And there is also a not quite advisable method:
strtok($value, ".");
This cuts of the first part until it encounters a dot. The result will be a string, not a PHP integer. While it doesn't affect using the result much, it's not the best option.
I see many answers, but the question is:
"Well i wanna remove the .587254564 and keep the 252, how can i do
that?"
Since the questioner is asking for php, the function in php will be the one for the job.
$newValue = floor($value);
In MySQL you can use:
select floor(field)
or in PHP you can use:
floor($value);