How to show number string value with plus or minus - php

I am trying to get number value with plus and minus
<?php
$num1= '-12.20000';
$num2= '+18.20000';
echo rtrim(str_replace('.00', '', number_format($num1, 2));
echo rtrim(str_replace('.00', '', number_format($num2, 2));
?>
Need output like
-12.2
+18.2

I can't see exactly what you need. There are not enough examples and your description of the task is not sufficient.
The number is formatted with a sign and 2 decimal places. If the last digit is a 0, it is removed with preg_replace().
$data = ['-12.20000','+18.20000', 234.0, 2.1234];
foreach($data as $value){
$formatVal = sprintf("%+0.2f",$value);
$formatVal = preg_replace('~(\.\d)0$~','$1',$formatVal);
echo $value.' -> '.$formatVal."<br>\n";
}
Output:
-12.20000 -> -12.2
+18.20000 -> +18.2
234 -> +234.0
2.1234 -> +2.12
If the result is only ever required with one decimal place, you can use
$formatVal = sprintf("%+0.1f",$value);
without the preg_replace.

In python, you could do it like this:
def returnWithSign(str):
n = float(str)
if n>0:
return '+{}'.format(n)
return n

Instead of using difficult functions in PHP just use the native stuff PHP brings with it. One fantastic thing of that stuff is the NumberFormatter class.
$formatter = new NumberFormatter( 'en_GB', NumberFormatter::DECIMAL );
$formatter->setTextAttribute(NumberFormatter::POSITIVE_PREFIX, '+');
$num1= '-12.20000';
$num2= '+18.20000';
echo $formatter->format($num1) . PHP_EOL;
echo $formatter->format($num2) . PHP_EOL;
Exactly does what you want.
Output: https://3v4l.org/UQX3Y

Related

four decimal zeros and no decimal point php

the code below is supposed to format the number i am getting after running multiplication in mysql to get data in a temporary table. problem is the result of the multiplication is not following the formatting. I want the number formatted to have four decimal places and the zeros retained.
<?php
$tv = $row_cscs_report['TOTAL_VALUE'];
$vr = str_replace('.', '', $tv);
echo $vr;
?>
You can do this using number_format, specifying 4 decimal places and telling it that the decimal and thousands separators should both be empty:
$tv = 3547.66;
echo number_format($tv, 4, '', '');
Output:
35476600
you can write like this:
<?php
$tv = $row_cscs_report['TOTAL_VALUE'];
$vr = sprintf("%.4f", $tv);
echo $vr;
?>
Reference:
http://php.net/manual/pl/function.sprintf.php

How to add commas and round decimals by checking value

I'm building an personal app where I can follow my cryptocurrency coins which I'm currently holding and following. The problem I've noticed are the decimals behind the price. A currency normally has max 2 decimals, but the API of Coinmarketcap gives me more depending on how much the price is.
Below is an example of the value I get from the API, and how I actually want the price to be shown. Values above 1000 will get a comma and no decimals.
$950194.0 -> $950,194
$81851.6 -> $81,852
$4364.97 -> $4,365
$326.024 -> $326.02
$35.0208 -> $35.02
$4.50548 -> $4.51
$0.0547128 -> $0.0547128
I've never tried something ever like this before, so I really don't know how to start. Tried using round() and numberFormat(), but couldn't make the same like how I wanted above in the example.
You can use money_format to make thing easier. However, the problem is about what precision do you want. You have to figure it out yourself since I cannot find the pattern from your examples. Yet I wrote the simple function for you with round and money_format. What the rest is adjust the precision to the point where you want in each case.
<?php
function my_money_format($number, $precision=0)
{
$number = preg_replace( '/[^0-9.,]/', '', $number); // clean the input
$number = round($number, $precision);
$format = '%.' . $precision . 'n';
setlocale(LC_MONETARY, 'en_US'); // set money format to US to use $
return money_format($format, $number);
}
echo my_money_format('$950194.0', 0); // $950,194
echo "\n";
echo my_money_format('$81851.6', 0); // $81,852
echo "\n";
echo my_money_format('$4364.97', 0); // $4,365
echo "\n";
echo my_money_format('$326.024', 2); // $326.02
echo "\n";
echo my_money_format('$35.0208', 2); // $35.02
echo "\n";
echo my_money_format('$4.50548', 2); // $4.51
echo "\n";
echo my_money_format('$0.0547128', 7); // $0.0547128
echo "\n";

How can I check if number has one , or two decimals?

I would like to know how I can check if a number has one or two decimals, and if it only has one decimal , like 12,9 for example, then echo the number with an additional 0, so it looks like 12,90.
<?php
$number = '12,9';
if $number //has 2 decimals // {
echo $number; }
else {
echo $number.'0';
}
endif;
?>
I have no clue how to do that properly, any help would be really appreciated! Thanks
If your input is a . (dot) separated decimal, you can just use number_format():
number_format('12.9', 2);
Alternatively, you can use the NumberFormatter class if you need to support multiple locales or numbers with commas for decimal separators. Such as:
$formatter = new NumberFormatter('de_DE', NumberFormatter::DECIMAL);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
echo $formatter->format($formatter->parse('12,9'));
Note: The use of NumberFormatter requires the intl extension. It can be added on debian based systems with a simple sudo apt-get install php5-intl.
If you're sure that the number is always formatted like you've posted, than you could do:
number_format(str_replace(',', '.', '12,9'), 2, ',', '.');
what you need is the number_format function
http://www.php.net/manual/en/function.number-format.php
Since PHP is not strictly typed, you could so something like this:
$parts = explode(",", $number);
$num_decimals = strlen($parts[1]);
if ($num_decimals == 2) //has 2 decimals // {
echo $number;
} else {
echo $number.'0';
}

function to return the numeric value

What would be an elegant way of doing this?
I have this -> "MC0001" This is the input. It always begins with "MC"
The output I'd be aiming with this input is "MC0002".
So I've created a function that's supposed to return "1" after removing "MC000". I'm going to convert this into an integer later on so I could generate "MC0002" which could go up to "MC9999". To do that, I figured I'd need to loop through the string and count the zeros and so on but I think I'd be making a mess that way.
Anybody has a better idea?
This should do the trick:
<?php
$string = 'MC0001';
// extract the part succeeding 'MC':
$number_part = substr($string, 2);
// count the digits for later:
$number_digits = strlen($number_part);
// turn it into a number:
$number = (int) $number_part;
// make the next sequence:
$next = 'MC' . str_pad($number + 1, $number_digits, '0', STR_PAD_LEFT);
using filter_var might be the best solution.
echo filter_var("MC0001", FILTER_SANITIZE_NUMBER_INT)."\n";
echo filter_var("MC9999", FILTER_SANITIZE_NUMBER_INT);
will give you
0001
9999
These can be cast to int or just used as they are, as PHP will auto-convert anyway if you use them as numbers.
just use ltrim to remove any leading chars: http://php.net/manual/en/function.trim.php
$str = ltrim($str, 'MC0');
$num = intval($str);
<php
// original number to integer
sscanf( $your_string, 'MC%d', $your_number );
// pad increment to string later on
sprintf( 'MC%04u', $your_number + 1 );
Not sure if there is a better way of parsing a string as an integer when there are leading zero's.
I'd suggest doing the following:
1. Loop through the string ( beginning at location 2 since you don't need the MC part )
2. If you find a number thats bigger than 0, stop, get the substring using your current location and the length of the string minus your current location. Cast to integer, return value.
You can remove the "MC" par by doing a substring operating on the string.
$a = "MC0001";
$a = substr($a, 2); //Lengths of "MC"
$number = intval($a); //1
return intval(str_replace($input, 'MC', ''), 10);

Php set value as a number

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.

Categories