﻿ Round a Double to 2 Decimal Places - ITCodar

# Round a Double to 2 Decimal Places

## Round a double to 2 decimal places

Here's an utility that rounds (instead of truncating) a double to specified number of decimal places.

For example:

``round(200.3456, 2); // returns 200.35``

### Original version; watch out with this

``public static double round(double value, int places) {    if (places < 0) throw new IllegalArgumentException();    long factor = (long) Math.pow(10, places);    value = value * factor;    long tmp = Math.round(value);    return (double) tmp / factor;}``

This breaks down badly in corner cases with either a very high number of decimal places (e.g. `round(1000.0d, 17)`) or large integer part (e.g. `round(90080070060.1d, 9)`). Thanks to Sloin for pointing this out.

I've been using the above to round "not-too-big" doubles to 2 or 3 decimal places happily for years (for example to clean up time in seconds for logging purposes: 27.987654321987 -> 27.99). But I guess it's best to avoid it, since more reliable ways are readily available, with cleaner code too.

(Adapted from this answer by Louis Wasserman and this one by Sean Owen.)

``public static double round(double value, int places) {    if (places < 0) throw new IllegalArgumentException();    BigDecimal bd = BigDecimal.valueOf(value);    bd = bd.setScale(places, RoundingMode.HALF_UP);    return bd.doubleValue();}``

Note that `HALF_UP` is the rounding mode "commonly taught at school". Peruse the RoundingMode documentation, if you suspect you need something else such as Bankers’ Rounding.

Of course, if you prefer, you can inline the above into a one-liner:

`new BigDecimal(value).setScale(places, RoundingMode.HALF_UP).doubleValue()`

### And in every case

Always remember that floating point representations using `float` and `double` are inexact.
For example, consider these expressions:

``999199.1231231235 == 999199.1231231236 // true1.03 - 0.41 // 0.6200000000000001``

For exactness, you want to use BigDecimal. And while at it, use the constructor that takes a String, never the one taking double. For instance, try executing this:

``System.out.println(new BigDecimal(1.03).subtract(new BigDecimal(0.41)));System.out.println(new BigDecimal("1.03").subtract(new BigDecimal("0.41")));``

Some excellent further reading on the topic:

• Item 48: "Avoid `float` and `double` if exact answers are required" in Effective Java (2nd ed) by Joshua Bloch
• What Every Programmer Should Know About Floating-Point Arithmetic

If you wanted String formatting instead of (or in addition to) strictly rounding numbers, see the other answers.

Specifically, note that `round(200, 0)` returns `200.0`. If you want to output "200.00", you should first round and then format the result for output (which is perfectly explained in Jesper's answer).

## Round up double to 2 decimal places

Use a format string to round up to two decimal places and convert the `double` to a `String`:

``let currentRatio = Double (rxCurrentTextField.text!)! / Double (txCurrentTextField.text!)!railRatioLabelField.text! = String(format: "%.2f", currentRatio)``

Example:

``let myDouble = 3.141let doubleStr = String(format: "%.2f", myDouble) // "3.14"``

If you want to round up your last decimal place, you could do something like this (thanks Phoen1xUK):

``let myDouble = 3.141let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"``

## How to round the double value to 2 decimal points?

There's no difference in internal representation between 2 and 2.00. You can use `Math.round` to round a value to the nearest integer - to make that round to 2 decimal places you could multiply by 100, round, and then divide by 100, but you shouldn't expect the result to be exactly 2dps, due to the nature of binary floating point arithmetic.

If you're only interested in formatting a value to two decimal places, look at `DecimalFormat` - if you're interested in a number of decimal places while calculating you should really be using `BigDecimal`. That way you'll know that you really are dealing with decimal digits, rather than "the nearest available `double` value".

Another option you may want to consider if you're always dealing with two decimal places is to store the value as a `long` or `BigInteger`, knowing that it's exactly 100 times the "real" value - effectively storing cents instead of dollars, for example.

## How do I round a double to two decimal places in Java?

Are you working with money? Creating a `String` and then converting it back is pretty loopy.

Use `BigDecimal`. This has been discussed quite extensively. You should have a `Money` class and the amount should be a `BigDecimal`.

Even if you're not working with money, consider `BigDecimal`.

## round up to 2 decimal places in java?

Well this one works...

``double roundOff = Math.round(a * 100.0) / 100.0;``

Output is

``123.14``

Or as @Rufein said

`` double roundOff = (double) Math.round(a * 100) / 100;``

this will do it for you as well.

## Round double in two decimal places in C#?

This works:

``inputValue = Math.Round(inputValue, 2);``

## Rounding a double value to x number of decimal places in swift

You can use Swift's `round` function to accomplish this.

To round a `Double` with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000:

``let x = 1.23556789let y = Double(round(1000 * x) / 1000)print(y) /// 1.236``

Unlike any kind of `printf(...)` or `String(format: ...)` solutions, the result of this operation is still of type `Double`.

EDIT:

## How do I convert a double to 2 decimal places?

Remember you can't use

`` String.format("%.2f", maltRequiredString);``

Because maltRequiredString is string. Correct coding is that you must use float in this function and for that you have to convert your string to float

``float f = Float.valueOf(maltRequiredString);  String test = String.format("%.02f", f);``

You can also use this technique for making it 2 decimal

``DecimalFormat decimalFormat = new DecimalFormat("#.##");float twoDigitsF = Float.valueOf(decimalFormat.format(f));``