Solved

How do I format a number?

Posted on 2002-04-29
1
179 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 50 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

Enroll in May's Course of the Month

May’s Course of the Month is now available! Experts Exchange’s Premium Members and Team Accounts have access to a complimentary course each month as part of their membership—an extra way to increase training and boost professional development.

Question has a verified solution.

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

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn different types of Android Layout and some basics of an Android App.
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 will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
Suggested Courses

734 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