truncating numbers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rotaryfreak
    New Member
    • Oct 2008
    • 74

    truncating numbers

    Hello,

    when i declare the variable:

    double num = 1.928761821237;

    if i want to display it with proper formatting, i will use a printf and set the number of digits i will display. Assuming i now want to truncate this number in memory to

    num = 1.92876;

    is there any way to do this and disregard the numbers that follow?

    thanks
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    If you are going to be changing the scale then why not use the BigDecimal class and set the scale to the required digits.

    Comment

    • chaarmann
      Recognized Expert Contributor
      • Nov 2007
      • 785

      #3
      Four additional ways:
      a)You can use printf to convert it to a string (with the exact number of wanted digits given in printf format string), and then convert it back from String to Number. You can also use DecimalFormat.f ormat() class for it.
      b) You can convert it to a String with String.valueOf( num), cut off the last digits with String.substrin g(), and then convert it back with Double.parseDou ble()
      c) You can multiply the number with a power of 10. If you want to trim away n digits, then you would multiply with Math.pow(10, n). In your case it's 10000. Then you can cut off the last digits with Math.round() or Math.rint() or Math.floor(), whatever suits you best. Then you would divide the result by the number you multiplied before (in your case 10000). But sometimes you get inaccurate results depending on your math processor hardware. So for high accuracy, but less speed, use functions of StrictMath package.
      d) best solution: download Jakarta Commons library MathUtils.
      Then use MathUtils.round (num, n) , which rounds the given value "num" to the specified number "n" of decimal places.

      Comment

      • rotaryfreak
        New Member
        • Oct 2008
        • 74

        #4
        thanks to both r035198x and chaarmann i'll try both methods and see which is simpler for me to use!

        thanks again!

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Also read the link about floating point arithmetic in the first (sticky) article in this group.

          kind regards,

          Jos

          Comment

          Working...