how to round the double value

schavalam
schavalam used Ask the Experts™
on
if the number is 1.4567 then i need out is 1.46 so what to.
i am using java.lang.Math.round(1.4567) getting output is 1 but i want 1.46
please help me
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Multiply it by 100, round it then divide it by 100.

Commented:
Hi schavalam:

use java.math.BigDecimal class. It is meant for this purpose only (currency fomatting, which as you know goes to 2 decimal points of precision like $23.75)

Taps


Top Expert 2016

Commented:
>>getting output is 1 but i want 1.46

You must be assigning it to an integral variable such as int or long. Assign to a double or float
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Commented:
CEHJ:  Math.round() returns a long or an int, so can't be used to round a double.

Not like you to miss that :-(
Top Expert 2016

Commented:
You're right ;-)
Commented:
if you just want to print it out,, try using a formatter(it automaticall rounds the value).

import java.text.DecimalFormat;

double d = 1.4567;
DecimalFormat df = new DecimalFormat(".00"); // set it to 2 decimal places
String output = df.format(d);

Commented:
Use the RoundUp/RoundDown option on BigDecimal.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial