PHP - number_format issues - php

number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...
42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9
I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.
Any ideas?

The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.
$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);

If anyone's interested in this, I've written a little function to get around this problem.
With credit to Joel Hinz above, I came up with...
function number_format_with_decimals($value, $round_to){
//$value is the decimal number you want to show with number_format.
//$round_to is the deicimal place value you want to round to.
$round_to_decimals = strlen(substr(strrchr($value, "."), $round_to));
$ans = number_format($value, $round_to);
return $ans;
}

I tried these solutions, but what ended up being my answer was this:
$output=money_format('%!i', $value);
This gives you something like 3,234.90 instead of 3,234 or 3,234.9

Related

scientific notation to normal decimal output conversion

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.

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.

Most efficient way to allow only one number after the decimal

I have a data set returned from yahoo finance api that is formatted like the following:
167.3B
97.719B
1.322B
973.4M
77.8M
I want to only allow one digit after the decimal. I can think of a number of ways to do it but they all seem somewhat cumbersome. Anyone know a best practice?
$letter = substr($number, -1);
$output = round($number, 1) . $letter;
This will round to the nearest 10th of an integer
You could do:
round(floor($number)*10)/10
If $number equaled 5.69 that would return 5.6, but rounding will be more accurate and is considered the best practice.
Another option:
number_format($number, 1)

number format for calculation

When 10000-100, then result should be 9900.
I tried when I use:-
< ?php
$num1 = number_format(round(10000,1),2);
$num2 = number_format(round(100,1),2);
echo $num1 - $num2;
?>
The above result is -90, that made me realize that the number_format function is not applicable in calculations.
Would there be any way that I can convert a value of number_format (obtained from POST from a previous page) back to numerical value for normal calculation?
To start, the reason is that:
(int) "10,000.00"
resolves to 10 since it stops parsing at the first non-numeric character. Thanks to PHP's weird type system, this is done implicitly when you subtract the strings.
Yes, you can strip out the commas easily:
$unformatted = str_replace(",", "", $formatted);
but it's cleaner to just post the raw numeric value (you can still use number_format for the displayed value).
EDIT: It is good practice to explicitly convert numeric strings (without commas) to float (or int) with either a cast ((int) or (float)) or the function version (intval or floatval).
I don't think you can perform this 10,000.00 -100.00 with the comma in the equation. Just perform the raw arithmetic operation then format the answer.
$num1 = 10000;
$num2 = 100;
echo number_format(round($num1 - $num2,1),2);
This outputs
9,900.00
There is an easier way.
number_format is for fomating output numbers or to round easy numbers.
number_format gives us power to make well fomed rounded numbers, for a better user experience.
For calcualtion and saving Numbers in your MYSQL Database use this.
Save your Numbers in MYSQL always as type DECIMAL not FLOAT. There are lots of bugs if you want to calculate with FLOAT fields.
Than use the english notation.
$number = 1234.56;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', ''); //
// 1234.57
And now you can calculate and save it, without any Bugs.
Always Remember yourself, Saving numbers into $var is always a string.
Yeah, you can deifine type, but it doesn't matter in first case, and its to long to explain here.
For more information about number_format see here -> http://php.net/manual/en/function.number-format.php

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