Change from string to variable - php

Hi Guys , just need a tiny help here . the green numbers on the right are strings . how do I change them to numbers ? Additionally I also need them to be 2 decimal place. What function do I use?? I tried the method below but the output was 0. Answers all welcome.
$profitText = $profitText*1;
$profitText = (float)$profitText;
round($profitText,2);
number_format($profitText, 2);
EDITED
Okay guys the deriving of this variable is really complex. every step has its functional purpose but heres the derivation. After the last profitText at the bottom, I realised this is now a string. why is that so? and how do I fix it?
$offeropen=$row['offerprice'];//1.3334
$pips=$offerpricepl-$offeropen;//difference btw prices , eg. 0.0023
$closedb=$offerpricepl;// nothing
$pips1=round($pips, 6);// round to 6 decimal points
$pips2 = str_replace('.', '', $pips1);// remove decimal
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);// methodology for adjusting figures and negative values back
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');// for triming 0 on the left
}
$pips3=$pips2/$minipipskiller;// methodology
$ticksize= "0.0001";// FOR PROFIT AND LOSS
$lot1 = "100000";
$sizecalc=$row['size'] * $lot1;
if ($row['type']=="buy")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
if ($row['type']=="sell")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
$zero= '0';
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$profitText=ltrim($profitText,'0');

Here's your problem:
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
You're trying to turn $profitText into a number. It's actually a string of HTML, and PHP can't manage to work out what it's supposed to do with it, so when you cast it to a number, it's returning 0.
Solution:
Use $profitandloss instead

this will do both requested points together:
$floatProfitVar = number_format($profit, 2, '.');

I think you need
floatval(mixed var)
http://www.php.net/manual/en/function.floatval.php
$profit = round(floatval(trim($profitText)), 2);
Proof: http://codepad.org/jFTqhUIk

The function you're looking for is sprintf or printf and has been designed for exactly that job:
printf('%.2F', '1.8'); # prints "1.80"
Demo: https://eval.in/44078
You can use string input for the float number parameter (F = float, locale independent) as well as integer or float input. PHP is loosely typed.
Use sprintf if you want to get back a string, printf prints directly.

$value = intval(floatval($profitText)*100)/100.0

I don't think this $profitText = $profitText*1; would work unless you first do $profitText = (float)$profitText;. Remember that you have to convert the string first before you can do any manipulation.
floatval(mixed $var) can also be used instead of typecasting but typecasting should work fine

Related

Convert a full string (represented in exponential format) back in number in PHP

I've been searching for converting my exponential number string into an exact number.
So, I've an exponential number stored as string in MySQL. I want to convert back this string in the exact number.
But It seems the number is quite big and crosses the boundary and provide me wrong data.
While I tried following code in various format but result is not in proper format.
policy_number = "2.9992020830803E+18";
number_format($policy_number, 0,'.','');
// Output
2999202083080300032
(float) $policy_number;
// Output
2.9992020830803E+18
sscanf($policy_number, "%f")[0];
// Output
2.9992020830803E+18
floatval($policy_number);
// Output
2.9992020830803E+18
gmp_init("2.9992020830803E+18");
gmp_strval($policy_number);
// Output
0
"2.9992020830803E+18" + 0;
// Output
2.9992020830803E+18
Please show me the right way to convert it.
Updated
I agree with Ed Cottrell that your problem is how you are storing your data in the db. However, if this is a project where you are already looking at a large set of data that is already stored as an exponent then this function I wrote should work for you. It should work for positive and negative bases and exponents. It basically mimics the way you would do the operation by hand.
I was not able to figure out a way to do it using math functions. If someone knows how to do it better please post. In the meantime, I had fun writing this.
Hope it helps you out!
function getRealNumber($number){
//Parse the base and exponent.
preg_match('/^(.*?)E[\-|\+](.*?)$/', $number, $data);
$base = $data[1];
$exp = $data[2];
//Test to see if the base is negative.
if(preg_match('/\-/', $base)){
$base = str_replace('-', '', $base);
$isNegative = TRUE;
}
//Capture the offset of the decimal point.
preg_match('/\./', $base, $position, PREG_OFFSET_CAPTURE);
$offset = $position[0][1]; //This is the offset of the decimal point.
$string = str_replace('.', '', $base); //Get numbers without decimal.
$length = strlen($string); //Get the length of string.
//Test to see if we are adding zeros to the end or beginning of string.
if(preg_match('/E\+/', $number)){
//Let's move the decimal.
if($length > ($exp + $offset)){
$string = substr_replace($string, '.', ($exp + $offset), 0);
} else {
$string = $string . str_repeat('0', $exp - ($length - $offset));
}
}elseif(preg_match('/E\-/', $number)){
//Calculate the number of zeros needed to add and append them.
if($offset > $exp){
$string = substr_replace($string, '.', $offset, 0);
} else {
$string = '0.' . str_repeat('0', $exp - $offset) . $string;
}
}
//Add the negative sign if we need to.
if(!$isNegative){
return $string;
} else {
return '-' . $string;
}
}
$policy_number = "2.9992020830803E+18";
echo getRealNumber($policy_number);
//Will output 2999202083080300000

Remove trailing zeros until 2 decimals in PHP

I've tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.
So how can I do this like the following conversion
11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
This might help, You can use sprintf given by PHP.
You can use float casting
echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;
and you have to check number of digits after decimal point and than get value like below :
$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
echo number_format($val,2);
}
You may use the round() function for this.
i-e round(number,precision,mode);
Example:
echo(round(11.2200,2));
Output
11.22
Thanks
Not sure if you need a fix for this anymore, but I just ran into the same problem and here's my solution:
$array = array(11.2200, 11.2000, 11.2340);
foreach($array as $x)
{
// CAST THE PRICE TO A FLOAT TO GET RID OF THE TRAILING ZEROS
$x = (float)$x
// EXPLODE THE PRICE ON THE DECIMAL (IF IT EXISTS)
$pieces = explode('.',$x);
// IF A SECOND PIECE EXISTS, THAT MEANS THE FLOAT HAS AT LEAST ONE DECIMAL PLACE
if(isset($pieces[1]))
{
// IF THE SECOND PIECE ONLY HAS ONE DIGIT, ADD A TRAILING ZERO TO FORMAT THE CURRENCY
if(strlen($pieces[1]) == 1)
{
$x .= '0';
}
}
// IF NO SECOND PIECE EXISTS, ADD A .00 TO IT TO FORMAT THE CURRENCY VALUE
else
{
$x .= '.00';
}
}

Converting to and from CENTS

So I know there have been multiple questions regarding Money and converting to and from cents.
Heck I have even asked another one, but I want to make a slightly different question so I hope there are no duplicates out there.
So I have created a function that takes a Dollar Value and sends it to CENTS.
But I think I have a slight problem with my code and hoping I can get it tweaked a little.
$money4 = "10.0001";
// Converted to cents, as you can see it's slightly off.
$money41 = "1001";
// So when "1001", get's put in the database, and then I return it back as a Money variable.
// We get, "$10.01"... but what I have now is a leak in my amounts... as it rounded up to the second point.
So to do what I have done, I have used to functions I made to do this.
// This essentially gets a DOLLAR figure, or the CENT's Figure if requested.
function stripMoney($value, $position = 0, $returnAs = "")
{
// Does it even have a decimal?
if(isset($value) && strstr($value, ".")) {
// Strip out everything but numbers, decimals and negative
$value = preg_replace("/([^0-9\.\-])/i","",$value);
$decimals = explode(".", $value);
// Return Dollars as default
return ($returnAs == "int" ? (int)$decimals[$position] : $decimals[$position]);
} elseif(isset($value)) {
// If no decimals, lets just return a solid number
$value = preg_replace("/([^0-9\.\-])/i","",$value);
return ($returnAs == "int" ? (int)$value : $value);
}
}
The next function I use is to generate the CENTS or return it back as dollars.
function convertCents($money, $cents = NULL, $toCents = TRUE)
{
if(isset($money)) {
if($toCents == TRUE) {
// Convert dollars to cents
$totalCents = $money * 100;
// If we have any cents, lets add them on as well
if(isset($cents)) {
$centsCount = strlen($cents);
// In case someone inputs, $1.1
// We add a zero to the end of the var to make it accurate
if($centsCount < 2) {
$cents = "{$cents}0";
}
// Add the cents together
$totalCents = $totalCents + $cents;
}
// Return total cents
return $totalCents;
} else {
// Convert cents to dollars
$totalDollars = $money / 100;
return $totalDollars;
}
}
}
And the final function that puts everything together. So we just use 1 function to merge the 2 functions together basically.
function convertMoney($value, $toCents = TRUE) {
if(isset($value) && strstr($value, ".")) {
return convertCents(stripMoney($value, 0), stripMoney($value, 1), $toCents);
} elseif(!empty($value)) {
return convertCents(stripMoney($value, 0), NULL, $toCents);
}
}
What I have done might be overkill, But I think it's fairly solid, other than this 1 detail, that I can see.
can anyone help me with these adjustments?
Do not use floating point arithmetic if you need exact answers. This applies to almost all languages, not just PHP. Read the big warning in the PHP manual.
Instead check out BC Math or the GMP extension. The latter only works with integer numbers so you are probably most interested in BC Math.
I think money_format is the function you were looking for...
<?php
$number = 1234.56;
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
// USD 1,234.56
// Italian national format with 2 decimals`
setlocale(LC_MONETARY, 'it_IT');
echo money_format('%.2n', $number) . "\n";
// Eu 1.234,56
?>

Convert a string containing a number in scientific notation to a double in PHP

I need help converting a string that contains a number in scientific notation to a double.
Example strings:
"1.8281e-009"
"2.3562e-007"
"0.911348"
I was thinking about just breaking the number into the number on the left and the exponent and than just do the math to generate the number; but is there a better/standard way to do this?
PHP is typeless dynamically typed, meaning it has to parse values to determine their types (recent versions of PHP have type declarations).
In your case, you may simply perform a numerical operation to force PHP to consider the values as numbers (and it understands the scientific notation x.yE-z).
Try for instance
foreach (array("1.8281e-009","2.3562e-007","0.911348") as $a)
{
echo "String $a: Number: " . ($a + 1) . "\n";
}
just adding 1 (you could also subtract zero) will make the strings become numbers, with the right amount of decimals.
Result:
String 1.8281e-009: Number: 1.0000000018281
String 2.3562e-007: Number: 1.00000023562
String 0.911348: Number: 1.911348
You might also cast the result using (float)
$real = (float) "3.141592e-007";
$f = (float) "1.8281e-009";
var_dump($f); // float(1.8281E-9)
Following line of code can help you to display bigint value,
$token= sprintf("%.0f",$scienticNotationNum );
refer with this link.
$float = sprintf('%f', $scientific_notation);
$integer = sprintf('%d', $scientific_notation);
if ($float == $integer)
{
// this is a whole number, so remove all decimals
$output = $integer;
}
else
{
// remove trailing zeroes from the decimal portion
$output = rtrim($float,'0');
$output = rtrim($output,'.');
}
I found a post that used number_format to convert the value from a float scientific notation number to a non-scientific notation number:
Example from the post:
$big_integer = 1202400000;
$formatted_int = number_format($big_integer, 0, '.', '');
echo $formatted_int; //outputs 1202400000 as expected
Use number_format() and rtrim() functions together. Eg
//eg $sciNotation = 2.3649E-8
$number = number_format($sciNotation, 10); //Use $dec_point large enough
echo rtrim($number, '0'); //Remove trailing zeros
I created a function, with more functions (pun not intended)
function decimalNotation($num){
$parts = explode('E', $num);
if(count($parts) != 2){
return $num;
}
$exp = abs(end($parts)) + 3;
$decimal = number_format($num, $exp);
$decimal = rtrim($decimal, '0');
return rtrim($decimal, '.');
}
function decimal_notation($float) {
$parts = explode('E', $float);
if(count($parts) === 2){
$exp = abs(end($parts)) + strlen($parts[0]);
$decimal = number_format($float, $exp);
return rtrim($decimal, '.0');
}
else{
return $float;
}
}
work with 0.000077240388
I tried the +1,-1,/1 solution but that was not sufficient without rounding the number afterwards using round($a,4) or similar

Just a question about str_replace

I have a question about str_replace in PHP. When I do:
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
print_r($latdir); gives :N52.2702777778
but print_r ($Latcoorl); gives :N52.270277777800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Yes, it adds a lot of zeros. Can someone explane this behavior just for the fun of it?
print_r ($latrichting);
give's: N
print_r ($Lat);
This give's the weird long number.
So its probably not the str_replace command, you think ?
$latmin2 = bcdiv($latsec, 60, 20);
$latmin_total = $latmin + $latmin2;
$lat = bcdiv($latmin_total, 60, 20);
$latdir = array("N" => 1, "S" => -1);
$latcoorl = $latdir * $latdir[$latrichting];
Happy New Year.
Your string replace search string has a space before the 'N' while the dumped value looks like it's N:
Not sure what it has to do with all the zeros though.
On my system this code fragment:
<?php
$latdir = ':N52.2702777778';
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
?>
gives the following result:
:N52.2702777778:N52.2702777778
My best guess is you have something after this code that prints out a serie of 0.
How I would do it; just a variation of Anthony's original answer that keeps everything as numeric and doesn't lapse into string mode.
$Latcoorl = ($latrichting == "N") ? ($Lat) : (-1 * $Lat);
The string operations you did won't generate any 0s.
The 0s have to come from $lat. What did you do with $lat? any division by pi? PHP will try to store the most accurate possible float number in $lat. That's not really a problem, its a correct behavior. Just truncate the number when displayed, or round it up.

Categories