get decimals after dot php
How to type decimal in PHP?
I keep a field in the database that has a decimal type.
How can I type this?
It is not working, because return:
Fatal error: Uncaught TypeError: Return value of getPrice() must be an instance of decimal, float returned.
Anyway type decimal not exists.
I can use float for typping, but is this safe and good? The point is that with the float type there can be numerical errors (Float or decimal for prices?).
3 Answers 3
Don’t listen to recommendation to use floats for money values. It’s really dangerous, because floating numbers cannot guarantee the accurate comparison of non-integer values.
Good solution is to use integers with multipliers. The best solution is to create ValueObject which represents type money.
If your prices are less than ten decimal places long, you’re fine.
However:
Never trust floating number results to the last digit, and do not compare floating point numbers directly for equality.
Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118.
How to get whole and decimal part of a number?
20 Answers 20
Then compare against 1/4, 1/2, 3/4, etc.
In cases of negative numbers, use this:
This code will split it up for you:
The floor() method doesn’t work for negative numbers. This works every time:
. also works for negatives (same code, different number):
Just to be different 🙂
As an added benefit, it will only split where both sides consist of digits.
a short way (use floor and fmod)
Cast it as an int and subtract
Or just to get the decimal for comparison
There’s a fmod function too, that can be used : fmod($my_var, 1) will return the same result, but sometime with a small round error.
PHP 5.4+
This is the way which I use:
Brad Christie’s method is essentially correct but it can be written more concisely.
This is equivalent to his method but shorter and hopefully easier to understand as a result.
If you can count on it always having 2 decimal places, you can just use a string operation:
No idea of performance but for my simple case this was much better.
Just a new simple solution, for those of you who want to get the Integer part and Decimal part splitted as two integer separated values:
This way is not involving string based functions, and is preventing accuracy problems which may arise in other math operations (such as having 0.49999999999999 instead of 0.5).
Haven’t tested thoroughly with extreme values, but it works fine for me for price calculations.
But, watch out! Now from -5.25 you get: Integer part: -5; Decimal part: -25
In case you want to get always positive numbers, simply add abs() before the calculations:
Finally, bonus snippet for printing prices with 2 decimals:
. so that you avoid getting 5.5 instead of 5.05. 😉
PHP: get number of decimal digits
Is there a straightforward way of determining the number of decimal places in a(n) integer/double value in PHP? (that is, without using explode )
18 Answers 18
You could try casting it to an int, subtracting that from your number and then counting what’s left.
I needed a solution that works with various number formats and came up with the following algorithms:
I used the following to determine whether a returned value has any decimals (actual decimal values, not just formatted to display decimals like 100.00):
This is procedural, kludgy and I wouldn’t advise using it in production code. But it should get you started.
Here’s a function that takes into account trailing zeroes:
If you want readability for the benefit of other devs, locale safe, use:
Solution
Explanation
In this case it’s string with three characters: 12.
preg_replace function converts these cached characters to an empty string «» (second parameter).
In this case we get this string: 1234555
strlen function counts the number of characters in the retained string.
Integers do not have decimal digits, so the answer is always zero.
Double/Float
Double or float numbers are approximations. So they do not have a defined count of decimal digits.
You can see two problems here, the second number is using the scientific representation and it is not exactly 1.2E-10.
String
For a string that contains a integer/float you can search for the decimal point:
First I have found the location of the decimal using strpos function and increment the strpos postion value by 1 to skip the decimal place.
Second I have subtracted the whole string length from the value I have got from the point1.
Third I have used substr function to get all digits after the decimal.
Fourth I have used the strlen function to get length of the string after the decimal place.
This is the code that performs the steps described above:
Show a number to two decimal places
What’s the correct way to round a PHP string to two decimal places?
The output should be 520.00 ;
How should the round_to_2dp() function definition be?
25 Answers 25
This function returns a string.
Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):
Description:
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Example #1 round() examples
Example #2 mode examples
The output will be:
You can use the PHP printf or sprintf functions:
Example with sprintf :
Alternatively, with printf :
Use the PHP number_format() function.
The output will be:
It will return 5.98 without rounding the number.
For conditional rounding off ie. show decimal where it’s really needed otherwise whole number
Use the PHP number_format() function.
This will display exactly two digits after the decimal point.
Advantage:
If you want to display two digits after a float value only and not for int, then use this.
Results from the above function:
New Correct Answer
Use the PHP native function bcdiv
round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.
However, my guess is doing this: number_format($number, 2);
The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.
If you want to use two decimal digits in your entire project, you can define:
Then the following function will produce your desired result:
But if you don’t use the bcscale function, you need to write the code as follows to get your desired result.
This will give you 2 number after decimal.
Number without round
Adding to other answers, since number_format() will, by default, add thousands separator.
To remove this, do this:
use roud(yourValue,decimalPoint) or number_format(yourValue,decimalPoint);
number_format() return value as string with like this 1,234.67. so in this case you can not use it for addition and any calculation.
In this case round() will be better option.
Here’s another solution with strtok and str_pad:
In case you use math equation like I did you can set it like this:
number_format
(PHP 4, PHP 5, PHP 7, PHP 8)
number_format — Format a number with grouped thousands
Description
Formats a number with grouped thousands and optionally decimal digits.
Parameters
The number being formatted.
Sets the separator for the decimal point.
Sets the thousands separator.
Return Values
Changelog
Examples
Example #1 number_format() Example
For instance, French notation usually use two decimals, comma (‘,’) as decimal separator, and space (‘ ‘) as thousand separator. The following example demonstrates various ways to format a number:
See Also
User Contributed Notes 38 notes
It’s not explicitly documented; number_format also rounds:
Outputs a human readable number.
if you want to benchmark all costs for 5 seconds:
(with ms meaning milliseconds and s meaning seconds)
I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.
I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.
You can change %03d to %04d, etc.
See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.
Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can’t be used to customize present number_format.
Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.
The ‘cents’ flag can force to never or always show 2 decimals
And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.
Just an observation:
The number_format rounds the value of the variable.
$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;
echo number_format($val1,2,»,»,».»); // returns: 1,23
echo number_format($val2,2,»,»,».»); // returns: 1,24
echo number_format($val3,2,»,»,».»); // returns: 1,24
//again check through array for non numerical characters but skipping allready processed keys
//if is not number remove from array
// Here is a function that produces the same output as number_format() but also works with numbers bigger than 2^53.
$original_number= 9223372036854775805;
echo a_number_format($original_number, 4, ‘.’,»‘»,3);
// Outputs: 9’223’372’036’854’775’805.1230
In my function my_number_format() [shown below] there was a bug.
Here is the corrected version:
?>
Thanks to Federico Cassinelli for the bug report.
[EDIT BY danbrown AT php DOT net: The original note follows.]
But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!
But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.
But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456
So, I created following function, that doesn’t change the amount of fractional digits:
A simple funtion to format american dollars.
To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):
What do you do if some of your numbers have decimal places, and some don’t? You can switch between functions, but if you’re building it in a loop, that’s not a good solution. Instead, we have the same as below, with a slight change:
function number_format_unlimited_precision($number,$decimal = ‘.’) <
$broken_number = explode($decimal,$number);
if($broken_number[1]==0) <
return number_format($broken_number[0]);
>else <
return number_format($broken_number[0]).$decimal.$broken_number[1];
>;
>;
formatting numbers may be more easy if u use number_format function.
I also wrote this :
function something($number)
<
$locale = localeconv();
return number_format($number,
$locale[‘frac_digits’],
$locale[‘decimal_point’],
$locale[‘thousands_sep’]);
>
function formats numbers of datetime type,
[ «zaman» ]= «1983-8-28 5:5:5» ;
Don’t forget to specify thousands_sep that default is ‘,’ to another value, otherwise function will return null.
This way, I use my 1st variable for calculations and my 2nd variable for output. I’m sure there are better ways to do it, but this got me back on track.
simpler function to convert a number in bytes, kilobytes.
?>
you may also add others units over PeraBytes when the hard disks will reach 1024 PB 🙂
If you want a number of digits after the point, but not unnecessary zeros.
Eg.
number_format(1.20000,4) = 1.2000
num_format(1.20000,4,0) = 1.2
number_format(1.20000,4) = 1.2000
num_format(1.20000,4,2) = 1.20
number_format(1.23456,4) = 1.2345
num_format(1.23456,4,2) = 1.2345
I’d like to comment to the old notes of «stm555» and «woodynadobhar».
They wrote about «number_format_unlimited_precision()».
I guess many of us need that kind of function, which is the almost same function as number_format but don’t round a number.
Does Anyone know any new solution in a recent PHP version?
If you use space as a separator, it will break on that space in HTML tables.
Furthermore, number_format doesn’t like ‘ ‘ as a fourth parameter. I wrote the following function to display the numbers in an HTML table.
function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores
I’m not sure if this is the right place anyway, but «ben at last dot fm»‘s ordinal function can be simplified further by removing the redundant «floor» (the result of floor is still a float, it’s the «%» that’s converting to int) and outer switch.
Note that this version also returns the number with the suffix on the end, not just the suffix.
This is a simple and useful function to convert a byte number in a KB or MB:
if you want as a separator and use windows charset this piece of code may help:
echo convertNumberToWordsForIndia ( «987654321» );
//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>