?
Solved

How do I format a number?

Posted on 2002-04-29
1
Medium Priority
?
181 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 35

Accepted Solution

by:
girionis earned 200 total points
ID: 6977218
 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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

752 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