Formatting Numbers with PHP [duplicate] - php

This question already has answers here:
Print numeric values to two decimal places
(6 answers)
Closed 11 months ago.
I'm saving numbers in MySQL using double(10,2).
The numbers are getting saved like:
456.2
232.20
764
On output, I want to force 2 decimals and add the necessary trailing zeros (currency).
Here is the function I'm using and it isn't working.
function format_currency_form($get_money) {
$money_output = abs(number_format($get_money, 2, '.', ''));
return $money_output;
}
(I'm using ABS because I want the value to display as a positive number regardless of its true value in the db)
Here is the code block used to output the data:
<?php echo format_currency_form($row_rs_data['trans_amount']); ?>
No errors getting thrown and no trailing zeros...
Any ideas?
Thanks
Brett

If you are dealing with currency try to use moneyformat
http://php.net/manual/en/function.money-format.php
money_format('%.2n', $number)
In your case the abs should be done in this way:
$number=-11.44;
$money_output = money_format('%.2n', abs($number));
echo $money_output;
If you are dealing with currencies (I think so) money_format gives you a lot of options.

Use sprintf to output formatted strings.
echo sprintf("%.2f", format_currency_form($blah_blah));

Related

php similar_text() gives different results on changing positions of string [duplicate]

This question already has answers here:
How does similar_text work?
(4 answers)
Closed 5 years ago.
I am using similar_text() function to Calculate the similarity between two strings.
$s1 = 'God is great';
$s2 = 'I too';
similar_text($s1, $s2, $result);
echo $result;
It gives output 11.764705882353
but when i interchange the position of strings, it gives different output:
$s1 = 'God is great';
$s2 = 'I too';
similar_text($s2, $s1, $result);
echo $result;
It gives output 23.529411764706
Why is this happen?
The function uses different logic depending of the parameter order. Check this question How does similar_text work?
This bug was reported without answer too https://bugs.php.net/bug.php?id=62648
Algorithm takes the first letter in the first string that second string contains, counts that, and throws away the chars before that from the second string. That is why it misses the characters in-between, and that's the thing causing the difference when you change the character order.
I'm not entirely sure why similar_text() produces different results, In the meanwhile, you can use levenshtein(), which will produce coherent results and do what you need, i.e.:
echo levenshtein ($s2, $s1);
# 11
echo levenshtein ($s1, $s2);
# 11

PHP round up or round down depending on decimal value [duplicate]

This question already has answers here:
Show a number to two decimal places
(25 answers)
Closed 6 years ago.
I have a php variable that I would like to round up if it closest value is i.e
113.845602277119 so this var would become 113.85
and round down if var is i.e 270.27388400703 would become 270.27 NOT 270.28
I presume i'll need a function to check the decimal value and update accordingly?
or a better example of what I want.
i.e this dynamic number 16.94502 I want this to round down to 16.94 the .9452 is closest to .95 but as the var is dynamic I need a check to do the inverse, other times the var could be 41.1378 is closest to .14 and so I want a round up
Use PHP round() function:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Example:
echo round(113.845602277119,2); // 113.85
echo round(270.27388400703,2); // 270.27
Hi You can use number_format for this
echo number_format("113.845602277119",2)."<br>"; // 113.85
echo number_format("270.27388400703",2)."<br>"; // 270.27
or round function
echo round("113.845602277119",2)."<br>"; // 113.85
echo round("270.27388400703",2)."<br>"; // 270
The PHP round function is perfect for this kind of work, you simply pass it the number and as a 2nd parameter pass it how many numbers to round to
You can view the documentation here http://php.net/manual/en/function.round.php
round(270.27388400703, 2)
round(113.845602277119, 2)

PHP replace characters "," in a string number to "." [duplicate]

This question already has answers here:
Unformat money when parsing in PHP
(8 answers)
Closed 7 years ago.
How to convert a string like "3,2563" to "3.2563",
$number = "3,2563" ;
setlocale(LC_MONETARY,"en_US");
echo money_format("%.4n", $number);
or
$number = number_format($number,4,".","");
Both examples output just 3.0000
The string "3,2563" is not a number, thus - it cannot be used as such.
It can easily be converted to a float number, using PHP function str_replace and type casting.
$number = "3,2563";
$number = (float)str_replace(",", ".", $number); // returns (float) 3.2563
// Do whatever you want to do. Now $number is a float.
Using str_replace, the , is replaced with a .
Note that the decimals separator can vary, depending on your PHP configuration.
"3,2563" is a string, you're trying to display a string as a number, that's not possible.
You can replace , with . before changing its type:
$number = "3,2563";
$number = str_replace(',', '.', $number); // get "3.2563"
$number = (float) $number; // get a floating number
setlocale(LC_MONETARY,"en_US");
echo money_format("%.4n", $number); // shows "3.2563"
echo money_format("%.2n", $number); // shows "3.26"
You're using a string ill-formatted for the desired use-case and existing logic you have in your code - i.e. '3,2563'. Let me be more clear. In some countries, a comma is used instead of a decimal to demarcate a whole unit of some currency and fractional units of some currency. In other cases, the comma and decimals indicate a thousand whole unit of some currency. It depends on what you're aiming for which isn't clear based on the example you gave... plus, I'm not aware of every monetary syntax convention.
In any event, the general procedure you want to employ is to remove all the commas or to normalize the number (for example use 32563 instead of 3,2563 if you're going for whole units), do your operations, and then reapply the convention (I assume that they're monetary conventions) that you want at the end. If you just want to replace the comma with a decimal - you can still use str_replace() to accomplish that as well. Build a function or class to do that so you can reuse that code for use with other similar problems.
My recommendation, though it wasn't explicit, is to simply use some str_replace() logic to generate a normalized/indexed number.

PHP Stripping leading zeros 0 from a number [duplicate]

This question already has answers here:
How to remove all leading zeroes in a string
(11 answers)
Closed 9 years ago.
I am posting this as this isn't something most newbies may be familiar with.
The Problem
We have a ticketing system which makes use of a numeric id. Now some people in the company prefer to pre-pend zeroes to the ticket number and some people would reference it without the leading zeroes which is the correct way. So to standardize the output we have to remove the leading zeroes.
This may sound simple to do, but we can't merely run a str_replace over it as this may remove valid 0's in the middle of the number.
Now you could preg match and do all sorts of funky things to find the answer, but the simplest is to merely cast the numeric string to an int.
Let's user the following as an example:
<?php
$correct = 45678;
$incorrect = 0045678;
echo $correct . '<br />';
echo $incorrect;
?>
And you should get the following printed out:
45678
0045678
Now essentially these are the same for the application, but I would like to be able to cater for people entering the information in the incorrect format.
Using ltrim:
$str="0045678";
$str = ltrim($str, '0');
echo $str;
you can also use ltrim() http://de3.php.net/manual/en/function.ltrim.php this removes the desired char from the left
Simplest Solution
As they say the simplest solution is often the best. And what is easier than telling PHP that this is an integer we are working with. We do this by pre-pending (int) to tell PHP that we are working with an integer.
Using the previous example:
<?php
$correct = 45678;
$incorrect = (int)0045678;
echo $correct . '<br />';
echo $incorrect;
?>
And you should get the following printed out:
45678
45678
I know it seems self explanatory, but I only learnt about type casting a couple of years into website development. Maybe you will find this of use.

issue in reversly printing a number in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does a leading zero do for a php int?
I am just a beginner in php. I tried to write program for print the given number as reverse. For example if i use 123 as input the result should be 321. I tried the following code. It works fine. But if the given input is 0123 the output is 38. I couldn't correct it. How can i correct my code? here is my code.
<?php
$n=123;
$b=0;
while($n>=1)
{
$b=$b*10+$n%10;
$n=$n/10;
}
echo $b;
?>
When you add a 0 to the beginning of your number, PHP treats the number as octal.
Octal 123 is decimal 83, which correctly changes to 38.
Just use the dynamic nature of PHP not much caring about the difference between numbers and strings:
echo strrev(123);
http://www.php.net/manual/en/function.strrev.php
Yes, it's because the numbers that are starting with 0 are considered in base 8, so 0123 is in fact 83 in base 10.
So, your algorithm is correct for integer numbers - if you want the revert of 0123 to be 3210, you could simply revert it as a string and you can simply use the strrev function
I think your math is the problem. You should have parenthesis around the multiplier and mod.
<?php
$num=6541020;
$revnum=0;
do{
$revnum=($revnum *10)+($num % 10);
$num=(int)($num / 10 );
}while($num>0);
echo $revnum;
?>
http://www.weberdev.com/get_example.php3?ExampleID=4879
you could use something like this:
<?php
$rprint = function ($nr) use (&$rprint)
{
echo $nr%10;
if($nr > 10)
{
$rprint($nr/10);
}
};
$rprint(12364);
?>
Edit 1:
OR you could use strings instead of numbers. As I suppose it was already suggested.
(I was a bit out of the subjects)
the integer with the leading zero is always treated as octal in php. So just make it as a string and use the buitin php function strrev()

Categories