0

How do I convert a number to a big decimal in PHP?

For example, I have a number: 788892,667.
I want to convert it to a big decimal: 788892667,
then convert it back to a long 788892,667.

Could I do this in PHP?

Pang
  • 9,564
  • 146
  • 81
  • 122
gungunst
  • 349
  • 1
  • 4
  • 5
  • 2
    php has no bigdecimal or long types, what is your question? – Iłya Bursov Mar 12 '14 at 02:17
  • I mean.. if in Java, the number can convert to bigdecimal. How about in PHP? could I do same like that in PHP? – gungunst Mar 12 '14 at 02:19
  • 1
    yes and no, as soon as there are no types - you cannot convert between types, as soon as internally php has type for storing number (it is called int and can be either 32 or 64 bits) you can have problems with math operations on string (with some long number), if you want to be sure that big numbers are handled correctly, you need to use any bignum library, like http://stackoverflow.com/questions/211345/working-with-large-numbers-in-php – Iłya Bursov Mar 12 '14 at 02:23

1 Answers1

3

PHP has no internal type for representing big numbers. What it does have is extensions to deal with such numbers: GMP and BCMath, but they are quite low-level.

If you want a library that provides BigDecimal and BigInteger, try brick/math (disclaimer: I'm the author):

use Brick\Math\BigDecimal;

$bigdecimal = BigDecimal::of('788892.667');    // BigDecimal(788892.667)
$biginteger = $bigdecimal->getUnscaledValue(); // BigInteger(788892667)
$int        = $biginteger->toInt();            // int(788892667)

This library makes use of the GMP and BCMath extensions when available, but also works without them, so it should be a good fit for any PHP project.

BenMorel
  • 34,448
  • 50
  • 182
  • 322