Solved

How do I format a number?

Posted on 2002-04-29
1
173 Views
Last Modified: 2011-09-20
How do I format a number in this example:

public class MyClass
{
     double d = 12.2386489583459;

     public String toString()
     {
          String str = ...     // need to be 12.2
          return str;
     }
}
0
Comment
Question by:s_lavie
1 Comment
 
LVL 35

Accepted Solution

by:
girionis earned 50 total points
Comment Utility
 You can use the java.text.DecimalFormat class. All you have to do is to define a pattern like:

Decimalformat df = new DecimalFormat("###.0");

  This means that you only need one decimal digit. If you want more then add more zero's in the constructor:

Decimalformat df = new DecimalFormat("###.0");

No you can call the format method like: df.format(<number>);

  In your example this is:

import java.text.DecimalFormat;

public class MyClass
{
    double d = 12.2386489583459;
    DecimalFormat df = new DecimalFormat("###.0");

    public String toString()
    {
         String str = df.format(d);
         return str;
    }
}

  Hope it helps.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mergeTwo  challenge 13 70
json format text only 4 64
word0 challenge 3 55
Groovy:unable to resolve class error 2 27
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now