Variable value gets rounded off

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on
hi all, while im computing large values the variable value gets
rounded off to the next higher value .How do we stop or prevent this
happening.

Re: Variable value gets rounded off

.oO(Lawrence)

How large is "large"? What about a code example?

Micha

Re: Variable value gets rounded off

\$a=\$b+\$c+\$d
where \$b=99999999999999
\$c=99999999999999
\$d=99999999999999

Re: Variable value gets rounded off

When a number gets too large for a 32-bit integer, PHP switches to floating
point.  An IEEE-754 floating point value holds just over 15 digits of
precision.  \$b, \$c and \$d fit, but \$a does not.  Hence, you lose precision.

If you need arbitrary precision mathematics, look at the BCMath functions
--
Tim Roberts, timr@probo.com
Providenza & Boekelheide, Inc.

Re: Variable value gets rounded off

The problem you are running into is integer overflow.  a 32 bit
integer can hold values of -~ 2 billion to +~2 billion, or 0 - ~4
billion depending on whether or not it is a signed integer.  Your sum,
while the inputs are integers, will result in an answer that is too
big to fit into an integer.  PHP has dynamic types so it will switch
to a floating point representation in this case.  Floating point
numbers cannot exactly represent some numbers, just like you can't
represent 1/3 in decimal.  Instead, the floating point result will
contain the closest approximation to the actual number instead.

In this case, what you need is not a floating point number, but what
is called a bignum instead.  Bignums chain smaller integers, or
strings depending on implementation, together in order to represent
larger values.  PHP provides a BCMath extension that includes support
for bignums, look at the BCMath documenatation on php.net.

Re: Variable value gets rounded off

thanx all of u,problem got solved by using bcadd