Smart questions
Smart answers
Smart people
Join Tek-Tips Forums
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Member Login




Remember Me
Forgot Password?
Join Us!

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips now!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

Join Tek-Tips
*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.
Jobs from Indeed

Link To This Forum!

Partner Button
Add Stickiness To Your Site By Linking To This Professionally Managed Technical Forum.
Just copy and paste the
code below into your site.

truncate to 2 decimals placesHelpful Member! 

lowbk (TechnicalUser) (OP)
26 Jul 05 4:36
hi, i need advice on truncating a double to a double of 2 decimal places. my method is written as

CODE

    private static double trancate(double x)
    {
        long y=(long)x*100;
        double z= (double)y/100;

        return z;
    }

strangely, the returned result has no decimals. i have tried DecimalFormat but it is returning a STRING instead of a double.
Helpful Member!  timw (Programmer)
26 Jul 05 5:21
Try -

CODE

private static double truncate(double x)
{
    long y=(long)(x*100);
    return (double)y/100;
}

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

lowbk (TechnicalUser) (OP)
26 Jul 05 5:53
thanks timw, it works. but i don't understand the logic behind. do you mind explaining?
timw (Programmer)
26 Jul 05 5:59
Certainly.

As you had it, the

CODE

long y=(long)x*100;

was casting the x to a long before it was multiplied by 100. So you were losing your fractional digits there. Putting brackets around the multiplication forces the cast to be performed on the result of the multiplication, thus preserving the fractional digits you were after.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

stefanwagner (Programmer)
26 Jul 05 21:28
For big doubles the method will produce garbage, I guess.

CODE


    public BigDoubleRounded ()
    {
        checkDouble (999999999999999999999999999999.999999999);
        checkDouble (0.9090909);
        checkDouble (1234.123456);
        checkDouble (9090909.9090909);
    }

    private void checkDouble (double d)
    {
        System.out.println ("d:\t" + d);
        System.out.println ("drunk:\t" + druncate (d));
        System.out.println ("trunc:\t" + truncate (d));
        System.out.println ("--------------");
    }

    private double druncate (double x)
    {
        long y = (long) (x * 100);
        return (double) y / 100;
    }

    private double truncate (double x)
    {
        DecimalFormat df = new  DecimalFormat ("0.##");
        String d = df.format (x);
        System.out.println ("\tformatted: " + d);
        d = d.replaceAll (",", ".");
        Double dbl = new Double (d);
        return dbl.doubleValue ();
    }
Locales may make your life complicated ...

seeking a job as java-programmer in Berlin: http://home.arcor.de/hirnstrom/bewerbung

timw (Programmer)
27 Jul 05 2:31
Okay then... what about

CODE

private static double truncate(double x){
  return Math.floor(x * 100)/100;
}

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

timw (Programmer)
27 Jul 05 3:07
... or to be correct for negative numbers too ...

CODE

private static double truncate(double x){
  if ( x > 0 )
    return Math.floor(x * 100)/100;
  else
    return Math.ceil(x * 100)/100;
}

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

stefanwagner (Programmer)
27 Jul 05 21:34
no good.

(x*100) will generate an overrun, if
(x > (Double.MAX_VALUE / 100))

seeking a job as java-programmer in Berlin: http://home.arcor.de/hirnstrom/bewerbung

timw (Programmer)
28 Jul 05 2:31
Yes. But it is then a decision by lowbk whether to take the performance hit of the longer solution which preserves the full Double range, or use the faster version which loses a small fraction of the Double range.

It depends on what he's using it for (which he doesn't state in the OP). Like a lot of things, it's a trade-off.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

stefanwagner (Programmer)
28 Jul 05 23:13
This is the output from the program

CODE

d:      1.0E30
drunk:  9.223372036854776E16
        formatted: 1000000000000000000000000000000
trunc:  1.0E30
--------------
d:      0.9090909
drunk:  0.9
        formatted: 0,91
trunc:  0.91
--------------
d:      1234.123456
drunk:  1234.12
        formatted: 1234,12
trunc:  1234.12
--------------
d:      9090909.9090909
drunk:  9090909.9
        formatted: 9090909,91
trunc:  9090909.91
If you may choose between a fast result and a correct result , the correct result is correct.

We shouldn't encourage beginners to use probably wrong results for (mostly irrelevant) performance-issuse.

Rules of Optimization:
Rule 1: Don't do it.
Rule 2: (for experts only): Don't do it yet.
(M. A. Jackson)

More computing sins are committed in the name of efficiency (without neccessarily achieving it) than for any other single reason - including blind stupidity.
(W. A. Wulf)

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil..
(Donald Knuth)

seeking a job as java-programmer in Berlin: http://home.arcor.de/hirnstrom/bewerbung

timw (Programmer)
29 Jul 05 2:29
Okay okay. I agree with you. Correct results are paramount unless there are strong identifiable reasons for eroding them in the name of efficiency.

One point however ... he wanted to truncate to 2 dps. You're solution appears to be rounding to the nearest 2 dps.

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

timw (Programmer)
29 Jul 05 3:14
I've tried to come up with a solution (truncate2) which will correctly truncate upto Double.MAX_VALUE without recourse to String manipulation.

CODE

  public static void main(String[] args) {
    checkDouble(999999999999999999999999999999.999999999);
    checkDouble(0.9090909);
    checkDouble(1234.123456);
    checkDouble(9090909.9090909);
    checkDouble(Double.MAX_VALUE);
    checkDouble(Double.MIN_VALUE);
  }
  
  private static void checkDouble (double d)
      {
          System.out.println ("d:\t" + d);
          System.out.println ("drunk:\t" + druncate (d));
          System.out.println ("trunc:\t" + truncate (d));
          System.out.println ("trunc2:\t" + truncate2 (d));
          System.out.println ("--------------");
      }

  private static double druncate(double x) {
    if ( x > 0 )
      return Math.floor(x * 100)/100;
    else
      return Math.ceil(x * 100)/100;
  }

  private static double truncate (double x){
    DecimalFormat df = new DecimalFormat("0.##");
    String d = df.format(x);
    System.out.println("\tformatted: " + d);
    d = d.replaceAll(",", ".");
    Double dbl = new Double(d);
    return dbl.doubleValue();
  }

  // A correct non-string solution????
  private static double truncate2 (double x){
    double fract;
    double whole;
    if ( x > 0 ){
      whole = Math.floor(x);
      fract = Math.floor( (x - whole) * 100) / 100;
    } else {
      whole = Math.ceil(x);
      fract = Math.ceil( (x - whole) * 100) / 100;
    }

    return whole + fract;
  }

This gives output :-

CODE

d:    1.0E30
drunk:    9.223372036854776E16
    formatted: 1000000000000000000000000000000
trunc:    1.0E30
trunc2:    1.0E30
--------------
d:    0.9090909
drunk:    0.9
    formatted: 0.91
trunc:    0.91
trunc2:    0.9
--------------
d:    1234.123456
drunk:    1234.12
    formatted: 1234.12
trunc:    1234.12
trunc2:    1234.12
--------------
d:    9090909.9090909
drunk:    9090909.9
    formatted: 9090909.91
trunc:    9090909.91
trunc2:    9090909.9
--------------
d:    1.7976931348623157E308
drunk:    9.223372036854776E16
    formatted: 17976931348623157000000000000000000000000000000 (and so on)
trunc:    1.7976931348623157E308
trunc2:    1.7976931348623157E308
--------------
d:    4.9E-324
drunk:    0.0
    formatted: 0
trunc:    0.0
trunc2:    0.0
--------------

Will this pass?

Tim
---------------------------
"Your morbid fear of losing,
destroys the lives you're using." - Ozzy

stefanwagner (Programmer)
29 Jul 05 20:46
From my perspective, yes.
lowbk has to decide, whether he likes a rounded-trunc, or a hard-trunc. :)

seeking a job as java-programmer in Berlin: http://home.arcor.de/hirnstrom/bewerbung

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Back To Forum

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close