converting from BigDecimal to BigInteger

Discussion in 'Java' started by Jeremy Watts, Feb 17, 2007.

  1. Jeremy Watts

    Jeremy Watts Guest

    I am trying to convert a BigDecimal number to a BigInteger one. I have
    truncated the number to its nearest whole integer firstly, before converting
    it to a string and then converting that to a BigInteger.... but the
    compilers coming back with an error message "Number Format Exception".

    Cant see what I'm doing wrong here... The number I'm using for the
    BigDecimal is
    '465836768828.000' . Is it the ".000" bit thats messing things up here?
    How would I remove that so that I'm left with 465836768828 ?

    Or is there a better way of converting between the two?

    Thanks
     
    Jeremy Watts, Feb 17, 2007
    #1
    1. Advertisements

  2. RTFM[1]

    BigInteger bi = mybigdecimal.toBigInteger();


    Regards, Lothar

    [1] http://java.sun.com/j2se/1.3/docs/api/java/math/BigDecimal.html
    --
    Lothar Kimmeringer E-Mail:
    PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

    Always remember: The answer is forty-two, there can only be wrong
    questions!
     
    Lothar Kimmeringer, Feb 17, 2007
    #2
    1. Advertisements

  3. Jeremy Watts

    Jeremy Watts Guest

    hee hee that simple eh? :) I'm sure I'd done this before somewhere
    without converting to strings first... anyway thanks
     
    Jeremy Watts, Feb 17, 2007
    #3
  4. Yes, the "." is not a permitted character: "The String representation
    consists of an optional minus sign followed by a sequence of one or more
    decimal digits."
    I half agree with the toBigInteger suggestion. If you expect your
    BigDecimal to always be an integer, you could use toBigIntegerExact,
    which throws an exception on data loss.

    Patricia
     
    Patricia Shanahan, Feb 17, 2007
    #4
  5. He didn't mention the Version of Java the program should work.
    toBigIntegerExact exists since 1.5.


    Regards, Lothar
    --
    Lothar Kimmeringer E-Mail:
    PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

    Always remember: The answer is forty-two, there can only be wrong
    questions!
     
    Lothar Kimmeringer, Feb 17, 2007
    #5
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.