Force currency format regardless of input - php

Regardless of what format the input is in, I am trying to use PHP to modify it, so the output is always consistent, rounds to two decimal places and has a dollar sign. My approach does not yield desired results all the time, I was wondering if someone can help me come up with a more robust solution?
Desired output:
$num = "$12.00"; //output $12.00
$num = "125"; //output $125.00
$num = "$300"; //output $300.00
$num = "17.5"; //output $17.50
$num = "1,777.5"; //output $1777.50
What I tried, however this does not work for all cases:
$num = "$" . str_replace("$", "", round($num,0)) . ".00";
I appreciate any advice! Many thanks in advance!

$num = "$" . str_replace("$", "", round($num,0));
In this line you round before you remove the $-sign. I must be the other way round:
$num = "$" . round(str_replace("$", "", $num),0);
EDIT: And to get the output you want, you might want to use number_format() instead of round()
$num = "$" . number_format(str_replace("$", "", $num),2, '.', '');

Related

PHP Check If String Contains Numbers and Check String Length

I'm trying to check if a username string is all numbers (but the field is not a numeric field). If so, I need the string to be 5 characters in length by adding leading 0's.
I have this code:
<?php
$getuname = $_GET['un'];
if (mb_strlen($getuname) <= 1){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 2){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 3){
$getuname = "0".$getuname;
}
if (mb_strlen($getuname) <= 4){
$getuname = "0".$getuname;
}
echo $getuname;
?>
The above code works for making sure the string is 5 characters by adding zeros, but it's not very pretty and I'm sure there is a much nicer way to do it. Anyone?
Also, this whole piece needs to be wrapped in an IF statement that is checking to see if it contains nothing but numbers in the first place. I tried using !is_numeric, but this doesn't seem to work. I'm assuming because it's not a numeric type field.
You can use is_numeric to check for a numeric field, it doesn't matter whether the variable is a string or not. See example here.
Then you can simply pad using str_pad()
if(!is_numeric($test))
echo $test . ' is not a number!';
else
echo str_pad($test, 5, 0, STR_PAD_LEFT);
Edit: as flixer pointed out, is_numeric() won't actually do what you specifically asked (to check that a string contains only digits, i.e. no periods, commas, dashes etc which would be considered to "be a number"). In this case, use ctype_digit() instead:
$test_number = '123.4';
$test_number2 = '12345';
echo ctype_digit($test_number) ? $test_number . ' is only digits' : $test_number . ' is not only digits';
echo ctype_digit($test_number2) ? $test_number2 . ' is only digits' : $test_number2 . ' is not only digits';
// output:
// 123.4 is not only digits
// 12345 is only digits
The key here is to avoid regex when you have better tools to do the job.
To add a little to this, ctype_digit() might return false when you pass in an integer variable: (example from PHP manual)
ctype_digit( '42' ); // true
ctype_digit( 42 ); // false - ASCII 42 is the * symbol
This can be OK, depending on the situation you're using this in. In your case you're validating a $_GET variable, which is always going to be a string so it won't affect you.
Docs:
str_pad(): http://php.net/str_pad
ctype_digit(): http://www.php.net/manual/en/function.ctype-digit.php
OP Here, this is it all together. Works like a charm...
if (ctype_digit($getuname) == true) {
$getuname = str_pad($getuname, 5, 0, STR_PAD_LEFT);
}
Use the str_pad() function. Like this:
$getuname = str_pad($_GET['un'], 5, '0', STR_PAD_LEFT);
Try this:
<?php
$getuname = $_GET['un'];
if(ctype_digit($getuname))
$getuname = str_repeat("0", 5-strlen($getuname)) . $getuname;
?>
Hope it works for u.
This should be a clean solution:
$getuname = $_GET['un'];
if(preg_match('/^\d+$/',$getuname)){
echo sprintf('%05d', $getuname);
}else{
// incorrect format
}
<?php
$getuname = $_GET['un'];
while (strlen($getuname) < 5) {
$getuname = '0' . $getuname;
}
echo $getuname;
?>

Padding zeroes to Price

$price = 10.00;
list($dollars, $cents) = explode('.', $price);
echo $dollars . '.' . $cents;
... almost works except that the zeros are omitted. 10.00 becomes 10 and 10.10 becomes 10.1
I see there's a padding function for strings, but anything for numbers or floats?
How do I fix this?
You can use number_format:
echo number_format($price, 2); // Would print 10.00
You can specify a separator for the decimal point and another one for the thousands:
echo number_format(1234.56, 2, ',', ' '); // Would print 1 234,56
Use Sprintf
$digit = sprintf("%02d", $digit);
For more information, refer to the documentation of sprintf.
number_format is what you want: http://php.net/manual/en/function.number-format.php
Though i would recommend number_format, you could use
sprintf('%02.2f', $price)
if you want to rely on string functions.

PHP: Max and Min returning incorrect results

I am sure this is because of the "g" on the end but this is the scenario and results when I try and work out a ratio percent. I always want to divide the highest of 2 numbers by the lowest.
$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"
$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"
PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"
It's type casting;
$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
result will be 175%
When you want to use your strings in mathematical operations, and you know that the unit is placed at the end as it is in your example, you can cast your variables to floats:
$item1_numeric = (float) $item1;
But obviously it is better to have the values and the units separated in your variables / database.
Use: substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.
You can't compare 2 strings with round().
Edit : If $item1 = "200g", ma solution is ok, but if if $item1 = "200.00g" you need to remove "." before round() with for example pregreplace.
Oh, YAPHPB - and one of my favorite ones. Even though it's written in the Doc:
When [max()] given a string it will be cast as an integer when comparing.
... it's only a partial truth: if at least one of compared values is a number, or a numeric string.
Otherwise all the strings will be compared as strings: first {0} characters of each strings will be compared, then {1}, then {2}... etc.
So basically that's what happens here:
echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
echo max("200.00g", 50); // "200.00g", as it gets converted to int (become 200)
And that's even more crazy:
echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
echo max("200.00", "1000.00"); // "1000.00", as we tried to help you, no, really!
The latter result can actually be predicted by someone knowing of numeric concept: when both strings are pure numbers, they got converted to numbers when compared. Still, I found this behavior unreliable, to say the least.
The bottom line: if you need to compare numbers, compare numbers, period. Type conversion in PHP can get real messy - and bite you in the bottom real hard when you least expect it. )

printing with the penny value in php

I have these value stored in a decimal 10,2 field
1052730
956700
How do i print this using php so that the value is like
$10,527.30
$9,567.00
basically i am trying to avoid the value as
$1,052,730 <--- this i dont want
You can use the
money_format($format, $value)
function in php. The details of the formatting is given here.
Well, assuming that 1052730 is really 10527.30 as alluded to in your question:
$number = 1052730;
$decimals = $number % 100; //30 in this case
$digits = floor($number / 100);
$paddedDecimals = str_pad($digits, 2, '0', STR_PAD_LEFT);
$out = '$' . number_format($digits, 0).'.'.$paddedDecimals;
echo $out; // $10,527.30
There are no floating point calculations used for the decimal part, so there's no need to worry about precision issues (although at this precision it would likely be hard to get a float error in there)...
Just divide by 100:
<?php
echo number_format(1052730/100, 2, '.', ',') . PHP_EOL;
echo number_format(956700/100, 2, '.', ',') . PHP_EOL;
printf ("$%01.2f", ($input / 100));

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