Results 1 to 4 of 4
  1. #1
    morello is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default More sensible BigDecimal toString()?

    The standard behaviour of BigDecimal.toString() makes no sense to me. In the JavaDoc you see

    [123, -1] "1.23E+3"

    Why would you ever want to show 1,230 as 1.23E+3?

    Is there a simple way to convert a BigDecimal to a string such that scientific notation is used if the exponent is bigger/smaller than a certain value, like a pocket calculator does?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: More sensible BigDecimal toString()?

    Your best bet for questions like these is to first check the API as it often will solve this problem a lot faster than we can. And in fact it does! Check out a method of BigDecimal that begins with toPlain...() in the BigDecimal API. You'll have to supply your own program logic to decide which method to call.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: More sensible BigDecimal toString()?

    The API also describes the sense behind the current (>1.4) toString() behaviour. It may not be what you want in some context, but it is as sensible as it could be.

  4. #4
    morello is offline Member
    Join Date
    Feb 2011
    Posts
    10
    Rep Power
    0

    Default Re: More sensible BigDecimal toString()?

    I'm puzzled why there is toPlainString and toEngineeringString but no toScientificString?

    toString doesn't guarantee producing scientific notation, so there are some numbers where you don't have the option of scientific format. OK, probably not numbers which you would want in that format.

    In practical terms, if I wanted scientific notation for numbers outside, say 10^8 and 10^-8, is toString always going to do that?

    Whether the behaviour of toString is as sensible as it could be is a matter of opinion - they have designed to be reversible and locale independent, but at the expense of readability and general usefulness IMHO.

Similar Threads

  1. Negating a BigDecimal
    By ryanmk54 in forum New To Java
    Replies: 5
    Last Post: 05-16-2011, 06:23 PM
  2. Divide bigdecimal again
    By ellhar in forum New To Java
    Replies: 3
    Last Post: 03-23-2011, 10:19 AM
  3. BigDecimal and BigInteger
    By jon80 in forum New To Java
    Replies: 8
    Last Post: 11-28-2010, 11:15 AM
  4. Using BigDecimal
    By doymand in forum New To Java
    Replies: 2
    Last Post: 10-30-2010, 09:25 AM
  5. BigDecimal question
    By orchid in forum New To Java
    Replies: 2
    Last Post: 08-12-2008, 01:44 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •