Solved

How do I format a number?

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

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

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…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

718 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