scientific notation to normal decimal output conversion - php

First of all, I have tried a lot to find exactly the same question but failed. There were similar solutions and solutions that looks nice but not for me.
In PHP, I want to convert(or properly print out) a number to page with echo or something like that.
The input numbers may vary like that:
100000000
10
0.1
0.0000000001
100000000.0000000001
They are retrieved from MySQL database. The field format is double
But, when I try to echo those numbers, small decimal number is printed with scientific notation
1E-11
I found out sprintf, number_format, stringfication, make (double), or (string) etc.. but they have some unwanted functions like below:
rounding number
redundant 0(zero) tailing : eg) 0.1 to 0.10000
I simply want to printout those number AS IS
and without redundant processes.
(like convert to decimal format by number_format followed by making it string then remove zero tailings)
How can I make it?

I found a way to do it myself and I am posting a quick answer.
function realval($v) {
$f = (string)number_format($v, 10, '.', ''); // 10000.0000010000
if(strpos($f, '.') !== false) { // if it's a decimal (if not, print as is)
$f = rtrim($f, "0"); // 10000.000001
$f = rtrim($f, "."); // to prevent 10000. like things.
}
return $f; // string format
}
This does what I needed. I wanted a more decent way to do so, but not figured out yet.

Related

PHP show float number in string

I want to show a float number in php string.
something like:
My float number is: 0.00003485
But when I am using echo I see it like this:
My float number is: 3.485E-5
Also, I know I can use printf("%.10f",$float) code, but I need to use it in lots of places in my string, So I can't use printf.
What code should I use on a string, to show floats as they are? I don't want that shorted number (3.485E-5).
At some condition i am prefer declaration float number as string:
MyFloatNumber = "0.0000000000000000000000003485";
so,
echo MyFlatNumber;
//0.0000000000000000000000003485
I know I can use printf("%.10f",$float) code, but I need to use it in lots of places in my string, So I can't use printf.
I have to respectfully disagree with that:
printf('My float number is: %1$.8f (again: %1$.8f; once more: %1$.8f)', 0.00003485);
Or, if you need it in a string:
$foo = sprintf('My float number is: %1$.8f (again: %1$.8f; once more: %1$.8f)', 0.00003485);
Of course, if you mean it's against project style guidelines or company policy, that's another story.
What code should I use on a string, to show floats as they are?
Really? Floats in PHP are a 64-bit IEEE 754 double precision format bitmap. According to this online converter, number 0.00003485 would be:
0010010001010111110011100001110100101110111001001111
Of course, they aren't actual ones and zeroes but different voltage levels ;-)
You can write a function to handle this in any way you want. Why not?
function fval($f, $precision = 9) {
return number_format($f, $precision);
}
Then any place you need to format, call it out:
$f = 3.485E-5;
echo fval($f); // this will print: 0.000003485

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 is converting decimal to exponential value [duplicate]

In PHP I have the following code:
<?PHP
$var = .000021;
echo $var;
?>
the output is 2.1E-5 !
Why? it should print .000021
Use number_format() to get what you're after:
print number_format($var, 5);
Also check sprintf()
2.1E-5 is the same number as 0.000021. That's how it prints numbers below 0.001. Use printf() if you want it in a particular format.
Edit If you're not familiar with the 2.1E-5 syntax, you should know it is shorthand for 2.1×10-5. It is how most programming languages represent numbers in scientific notation.
Use number_format or sprintf if you want to see the number as you expect.
echo sprintf('%f', $var);
echo number_format($var, 6);
To show a number up to 8 decimal spaces, without extra zeroes to the right (as number_format does, which can be annoying), use this:
echo rtrim(rtrim(sprintf('%.8F', $var), '0'), ".");
In general, a number is a number, not a string, and this means that any programming language treats a number as a number. Thus, the number by itself doesn't imply any specific format (like using .000021 instead of 2.1e-5). This is nothing different to displaying a number with leading zeros (like 0.000021) or aligning lists of numbers. This is a general issue you'll find in any programming language: if you want a specific format you need to specify it, using the format functions of your programming language.
Unless you specify the number as string and convert it to a real number when needed, of course. Some languages can do this implicitly.
The previous answers responded to OP question, but none offered the code to do it.
Use this function to format any number with E- format.
function format_amount_with_no_e($amount) {
$amount = (string)$amount; // cast the number in string
$pos = stripos($amount, 'E-'); // get the E- position
$there_is_e = $pos !== false; // E- is found
if ($there_is_e) {
$decimals = intval(substr($amount, $pos + 2, strlen($amount))); // extract the decimals
$amount = number_format($amount, $decimals, '.', ','); // format the number without E-
}
return $amount;
}
Please note the function will always return a string.
Programming languages have different methods for storing numbers in memory. This is determined by the type of number that is being used. In your case, you have a floating point number (a fraction) that is to large to be stored as a fixed point number ( fractions are stored in this manner depending on their size).
This is a very important feature especially when working with very large or very small numbers. For instance, NASA or spaceX uses special storage methods for its calculations to ensure that the rockets the re-enter earths orbit land where they should.
Also, different storage methods take up different amounts of memory. However, the solution provided above should work. Just remember round off errors might occur with very big or small numbers.

PHP Long string. Output it all

So I got a really long string, made by a calculator.
$string='483451102828322427131269442894636268716773727170';
$result=(8902543901+$string)*($string/93.189)/($string)+55643907015.57895461;
echo $result;
This outputs 5.1878558931668E+45
So now my question is. How can I output the whole string, without that nasty E+45?
PHP on a 64 bit machine can only accurately calculate number up until 9223372036854775807. As soon as you calculate with numbers higher than that, php will switch to floats which may loose some of it's precision, especially when you use divisions.
There's an extension for php that will allow you to make calculations based on string, called BCMath.
Example:
$string = '483451102828322427131269442894636268716773727170';
$result = bcadd($string, 8902543901);
echo $result;
bcadd() is for additions, bcdiv() for divisions and bcmul() for multiplying.
You can't print exact value because you are using calculation, so this $string becomes a number (float in this case) and all numbers have limited precision.
If you want to do operations on big numbers you should use BCMath
However if you want to display it without scientific notation you can do it using:
echo sprintf("%f",$result);
or
echo sprintf("%.0f",$result);
if you want to omit decimal part

Why is PHP printing my number in scientific notation, when I specified it as .000021?

In PHP I have the following code:
<?PHP
$var = .000021;
echo $var;
?>
the output is 2.1E-5 !
Why? it should print .000021
Use number_format() to get what you're after:
print number_format($var, 5);
Also check sprintf()
2.1E-5 is the same number as 0.000021. That's how it prints numbers below 0.001. Use printf() if you want it in a particular format.
Edit If you're not familiar with the 2.1E-5 syntax, you should know it is shorthand for 2.1×10-5. It is how most programming languages represent numbers in scientific notation.
Use number_format or sprintf if you want to see the number as you expect.
echo sprintf('%f', $var);
echo number_format($var, 6);
To show a number up to 8 decimal spaces, without extra zeroes to the right (as number_format does, which can be annoying), use this:
echo rtrim(rtrim(sprintf('%.8F', $var), '0'), ".");
In general, a number is a number, not a string, and this means that any programming language treats a number as a number. Thus, the number by itself doesn't imply any specific format (like using .000021 instead of 2.1e-5). This is nothing different to displaying a number with leading zeros (like 0.000021) or aligning lists of numbers. This is a general issue you'll find in any programming language: if you want a specific format you need to specify it, using the format functions of your programming language.
Unless you specify the number as string and convert it to a real number when needed, of course. Some languages can do this implicitly.
The previous answers responded to OP question, but none offered the code to do it.
Use this function to format any number with E- format.
function format_amount_with_no_e($amount) {
$amount = (string)$amount; // cast the number in string
$pos = stripos($amount, 'E-'); // get the E- position
$there_is_e = $pos !== false; // E- is found
if ($there_is_e) {
$decimals = intval(substr($amount, $pos + 2, strlen($amount))); // extract the decimals
$amount = number_format($amount, $decimals, '.', ','); // format the number without E-
}
return $amount;
}
Please note the function will always return a string.
Programming languages have different methods for storing numbers in memory. This is determined by the type of number that is being used. In your case, you have a floating point number (a fraction) that is to large to be stored as a fixed point number ( fractions are stored in this manner depending on their size).
This is a very important feature especially when working with very large or very small numbers. For instance, NASA or spaceX uses special storage methods for its calculations to ensure that the rockets the re-enter earths orbit land where they should.
Also, different storage methods take up different amounts of memory. However, the solution provided above should work. Just remember round off errors might occur with very big or small numbers.

Categories