Convert strings to numbers without losing decimals - php

I'm developing a map and I have to save this parameters on Parse database:
lat.: 20.6350 . Long: -103.5334
The problem is when i convert them into numbers, that function converts 20.6350 to 20.635. ¿What can I do in order tu preserve the last zero?

You should specify the sig figs and they will display properly.
$lat = "20.6350";
$lng = "-103.5334";
print number_format($lat, 4); // 4 sig figs
print number_format($lng, 4);
See http://php.net/number_format for additional formatting info
UPDATE
Based on your comments above, seems the string you're pulling varies in length, correct?
Why not just get the amount of sig figs after the decimal then use that as the second argument in number_format()? I'm sure there is a more appropriate way to handle, but this would work I believe.
// Calculate sig figs
$length = strlen($lng) - (stripos($lng, '.') + 1);
number_format($lng, $length);
or in one line
number_format($lng, strlen($lng) - (stripos($lng, '.') + 1));

if you want the numbers with four decimals in your database you could use the Decimal type. Under length you could enter 6,4 representing maximum of 6 digits in total and 4 digits behind the point.
If you want to display the number in PHP you could use the number_format() function
echo number_format($longitude, 4);

Related

PHP Retain all decimals when using abs function

I'm using the abs function to get the positive value of a negative number as follows:
$totalTax = -4.50 ;
echo abs($totalTax);
which is working well except it is dropping the 0 and returns 4.5 instead of 4.50.
Not sure why it's doing this or what the best method to retain all digits when using the abs function to convert a negative number to a positive? I need the 2 decimals regardless if the cents value is 0 for importing into an accounting system which only accepts 2 decimals and not 1.
It's just because how PHP outputs leading/trailing zeros - trims them. Because there is infinite number of zeros after last non-zero number
e.g. echo 00000.1000000 will output 0.1
You should format your number to keep that leading and trailing zeros.
echo number_format($totalTax, 2, '.', '');
// -> 4.50
You can try with the number_format() function. There is no possibility to retain trailing 0 with using only the abs() function.
Here is code you try:
$totalTax = -4.50 ;
$total_sub = abs($totalTax);
echo number_format($total_sub, 2);

Prevent number_format from rounding numbers - add commas and keep the decimal point - PHP

Number format adds the commas I want but removes the decimals.
echo number_format("1000000.25");
This returns 1,000,000
I want it to return 1,000,000.25
I need both the commas and the decimals, without any number rounding. All my values are decimals. They vary in length.
Do I have to use something other than number format?
In case what you meant by they vary in length is related to the decimal part, take a look at this code:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
Some tests
Output for 1000000.255555:
1,000,000.255555
Output for 1000000.25:
1,000,000.25
Output for 1000000:
1,000,000
It counts how many chars there are after the . and uses that as argument in the number_format function;
Otherwise just use a constant number instead of the function call.
And some reference...
From the manual -> number_format():
string number_format ( float $number [, int $decimals = 0 ] )
And you can see in the description that
number
The number being formatted.
decimals
Sets the number of decimal points.
And a bit more:
[...]If two parameters are given, number will be formatted with decimals
decimals with a dot (".") in front, and a comma (",") between every
group of thousands.
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
Explanation:
Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs. This Stack overflow answer tells you how to get the number of decimal places of your provided string
The docs for number_format() indicate the second parameter is used to specify decimal:
echo number_format('1000000.25', 2);
Ref: http://php.net/manual/en/function.number-format.php

Format number from (-/+)xx.xxxxxxxxx to xxxx.xxxx in PHP

i need to arrange a number to a format like this xxxx.xxxx. But I get as input something like this (-/+)xx.xxxxxxxxx.
If the number is x.xx it should get the above mentioned format by adding 0s to end and front.
please guide me on the correct way to get this done!
You can use explode & str_pad -
$num = 7.89;
$temp = explode('.', $num);
echo str_pad($temp[0], 4, 0, STR_PAD_LEFT).'.'.str_pad($temp[1], 4, 0, STR_PAD_RIGHT);
Output
0007.8900
You can use sprintf("%f4.6");
The number before the dot would determine de number of digits fot the integer part and de other, the number of decimals

PHP Number Formatting

I have been trying all morning but how would I this number 1304583496 to look like this
13.04583496
and the same goes for this number
456604223 to 4.56604223
There are always 8 numbers to the right.
Divide it with 100000000, or use "pow" function:
$number / pow(10, 8);
You could also use the official number_format method after division to keep your ending zeroes and have your number displayed in a nice manner.
<?php
$num = 1304583496; //the number
echo number_format($num/100000000,8,"."," "); //number of decimals = 8, comma seperator is . and thousands seperator is a space here
?>
For more information on this function: http://www.w3schools.com/php/func_string_number_format.asp

Advanced Php Number Formatting

I want to have a PHP number formatted with a minimum of 2 decimal places and a maximum of 8 decimal places. How can you do that properly.
Update: I'm sorry, my question is say I have number "4". I wish for it to display as "4.00" and if I have "2.000000001" then it displays as "2.00" or if I have "3.2102" it will display as such. There is a NSNumber formatter on iPhone, what is the equivalent in PHP.
This formats the $n number for 8 decimals, then removes the trailing zero, max 6 times.
$s = number_format($n, 8);
for($i=0; $i<8-2; $i++) {
if (substr($s, -1) == '0')
$s = substr($s, 0, -1);
}
print "Number = $s";
Use sprintf() to format a number to a certain number of decimal places:
$decimal_places = 4;
$format = "%.${decimal_places}f";
$formatted = sprintf($format,$number);
I don't understand why you would want to display numbers to an inconsistent degree of accuracy. I don't understand what pattern you're trying to describe in your comment, either.
But let us suppose that you want the following behaviour: you want to express the number to 8 decimal places, and if there are more than 2 trailing zeroes in the result, you want to remove the excess zeroes. This is not much more difficult to code than it is to express in English. In pseudocode:
$mystring = string representation of number rounded to 8 decimal places;
while (last character of $mystring is a 0) {
chop off last character of $mystring;
}
Check the number format function:
<?php
$num = 43.43343;
$formatted = number_format(round((float) $num, 2), 2);
?>
http://php.net/manual/en/function.number-format.php
Using preg_match just get the zero ending with and then rtim it
<?php
$nn = number_format(10.10100011411100000,13);
preg_match('/[0]+$/',$nn,$number);
if(count($number)>0){
echo rtrim($nn,$number[0]);
}
Hope it will help you.

Categories