Why Is PHP Printing My Number in Scientific Notation, When I Specified It as .000021

how to prevent float variables displaying as scientific notation when printing

This is the scientific notation of float number. So, if you want to format then you should use number_format() function.
Below example the second parameter will tell at what precision do you need.
So, as per your example you should use 14.

Try this:

$var = number_format((float)-0.00000025478625, 14);
print($var);

(PHP) How to avoid scientific notation and show the actual large numbers?

You can use standard bc_math library to handle operations with large numbers. Please, note, that in this case your numbers will be represented as strings, but library provides specific methods for operations under such strings.

PHP - Convert number to scientific notation

You can convert to scientific notation using the %e or %E format specifiers to sprintf/printf.

e The argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).

E Like the e specifier but uses uppercase letter (e.g. 1.2E+2). – https://www.php.net/manual/en/function.sprintf.php

To get a certain number of digits after the decimal point, you can use a precision specifier e.g. %.14e

Here's an example from the sprintf manual.

Example #6 sprintf(): scientific notation


<?php $number = 362525200;

echo sprintf("%.3e", $number); ?>

The above example will output:

3.625e+8

php scientific notation format

There is no built-in method as far as I know. But with a little bit of Regex black magic you can do something like this:

preg_replace('/(E[+-])(\d)$/', '${1}0$2', sprintf('%1.2E',$var));

Notice that I just wrapped your call to sprintf() with an appropriate call to preg_replace(). If the regular expression does not match it will leave the output from sprintf() as is.



Related Topics



Leave a reply



Submit