Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: How do I print a double to 2 significant figures?

  1. #1
    Junior Member
    Join Date
    Aug 2017
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default How do I print a double to 2 significant figures?

    In my toString I'm trying to print the total cost as $9.30. It is printing as $9.3 - without the 0 on the end.

    This looks like:

    public String toString()
    {
         return "$"+total;
    }

    However my "total" variable must be of type double, I've tried casting it with (float)total which hasn't worked. Do I need to save total into a float variable out of the toString or is there another way I can get it to appear as $9.30

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    22,407
    Thanks
    53
    Thanked 2,399 Times in 2,352 Posts

    Default Re: How do I print a double to 2 significant figures?

    See the Formatter class for useful method to format a numeric value as you want to see it.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Is there any significant difference between these segments of code?
    By bihlas in forum Java Theory & Questions
    Replies: 5
    Last Post: June 19th, 2014, 01:37 PM
  2. Replies: 1
    Last Post: December 3rd, 2012, 02:35 PM
  3. [SOLVED] Read double from console without having to read a string and converting it to double.
    By Lord Voldemort in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: June 26th, 2011, 08:08 AM

Tags for this Thread