Solved

How do I format a number?

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Android studio getdrawable(int) is deprecated 4 36
groupSumClump challenge 9 98
topping2 challenge 13 80
mockito example issue 8 62
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
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…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

929 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

9 Experts available now in Live!

Get 1:1 Help Now