In PHP i have define a variable with 19 digit long number and then print it. But it changes into exponential NUmber which is not acceptable in API Use. I need it as NUMBER. Here is an example of Problem.
$a = 1435483000000072013;
echo $a;
adn it returns 1.4354830000001E+18
Also, I have tried following function but it return wrong number
function output($x) {
$f = sprintf('%0.08f', $x);
$f = rtrim($f,'0');
$f = rtrim($f,'.');
return $f;
}
echo output(1435483000000072013);
this returns me 1435483000000071936 Number changes
So what is solution for this??
Champ, PHP doesn't have strictly typed variables, but it still has to decide whether your number is an int, a float or a double when it stores the information. And your number is larger than INT_MAX, so it's not going to fit into an integer format. That means the system has to bump it up to at least a float, which is where you're getting the exponential format from.
See NoGray's solution for how to fix it. Your number is still being stored, it's just being represented differently because your number is too big.
You can use number_format with an empty string for the thousands separator
e.g.
$a = 1435483000000072013;
echo number_format($a, 0, '.', '');
$a = 1.435483000000072013;
printf("%.18f",$a);
Related
I made this function. It seemed it's working but when it comes to 20 digits number, the return value was 19. I'm wondering why this problem happen..
My function
function sumDigits($n) {
return strlen($n);
}
echo sumDigits(100); //3
echo sumDigits(1000); //4
echo sumDigits(12345); //5
echo sumDigits(1000000000); //10
echo sumDigits(145874589632); //12
echo sumDigits(0); //1
echo sumDigits(12345698745254856320); //19 <-- Why not 20?
Can you please somebody explain for me?
Thank you so much.
First, I would point out that the name of your function is misleading, as you are not really summing the values of the digits, but are counting the digits. So I would call your function countDigits instead of sumDigits.
The reason why it doesn't work for large numbers, is that the string representation will switch to scientific notation, so you're actually getting the length of "1.2345698745255E+19" not of "12345698745254856320"
If you are only interested in integers, you will get better results with the logarithm:
function countDigits($n) {
return ceil(log10($n));
}
For numbers that have decimals, there is no good solution, since the precision of 64-bit floating pointing point numbers is limited to about 16 significant digits, so even if you provide more digits, the trailing decimals will be dropped -- this has nothing to do with your function, but with the precision of the number itself. For instance, you'll find that these two literals are equal:
if (1.123456789123456789123456789 == 1.12345678912345678) echo "equal";
Because you function parameter is an integer, exceeding the limit.
If you dump it, it actually shows the following:
1.2345698745255E+19 - which is 19 letters.
If you would do the following, it will return 20 - mind the quotes, which declares the input as string.
echo sumDigits("12345698745254856320"); //19 <-- Why not 20? -> now will be 20
As per documentation, strlen() expects a string so a cast happens. With default settings you get 1.2345698745255E+19:
var_dump((string)12345698745254856320);
string(19) "1.2345698745255E+19"
The root issue is that PHP converts your integer literal to float because it exceeds PHP_INT_MAX so it cannot be represented as integer:
var_dump(12345698745254856320, PHP_INT_MAX);
In 64-bit PHP:
float(1.2345698745254857E+19)
int(9223372036854775807)
You could change display settings to avoid E notation but you've already lost precision at this point.
Computer languages that store integers as a fixed amount of bytes do not allow arbitrary precision. Your best chance is to switch to strings:
var_dump('12345698745254856320', strlen('12345698745254856320'));
string(20) "12345698745254856320"
int(20)
... and optionally use an arbitrary precision library such as BCMath or GMP if you need actual maths.
It's also important to consider that this kind of issues is sometimes a symptom that your input data is not really meant to be an integer but just a very long digit-only string.
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.
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.
I have a situation where all records in a CSV I'm parsing are currency, but the values are not separated by a decimal point. So for instance, value '1234' is actually '12.34', and '12345' is '123.45'.
I'm struggling to find a way to manually convert these values into decimals. I can't user number_format, because it will give me an output like so:
$original_num = 1234;
$formatted_num = number_format($original_num, '2', '.', '');
$formatted_num = 1234.00; //Output
The other issue is that sometimes I may have a value like '436257.5' after I combine two numbers, which is actually '436.2575' so I can't just manually push in a '.' two places from the end of the string. Should I consider formatting it differently while I'm parsing the file?
Assuming you're using integers to always represent decimals with 2 places of precision after the decimal point, you just divide with 100 to insert the dot in the right place.
What do you mean, "combine"? You mean multiply? You should renormalise after each multiplication, and never get into a situation where you're representing decimals of differing precisions (unless you keep track of the precision, which you can do but it's pain in the ass and normally unnecessary).
function multiply($a, $b) {
return round($a * $b / 100);
}
function format($a) {
return sprintf("%.2f", $a / 100);
}
Since number_format() function always adds 2 00 as decimal, you can divide the value by 100.
number_format($original_num/100,2);
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.