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.
So, use this instead
(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 // true
1.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
anddouble
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).
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.
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.141
let 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.141
let doubleStr = String(format: "%.2f", ceil(myDouble*100)/100) // "3.15"
How to get a Double value up to 2 Decimal places
You can simply do this:
let pi = 3.14159
let text = String(format: "%.2f", arguments: [pi])
print(text) // output = 3.14
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.23556789
let 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:
Regarding the comments that it sometimes does not work, please read this: What Every Programmer Should Know About Floating-Point Arithmetic
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
.
Best way to Format a Double value to 2 Decimal places
No, there is no better way.
Actually you have an error in your pattern. What you want is:
DecimalFormat df = new DecimalFormat("#.00");
Note the "00"
, meaning exactly two decimal places.
If you use "#.##"
(#
means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d);
prints just "3"
, not "3.00"
.
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.
How to get a Double value up to 2 Decimal places
You can simply do this:
let pi = 3.14159
let text = String(format: "%.2f", arguments: [pi])
print(text) // output = 3.14
Related Topics
Search Multiple Words in One String in Swift
Best Way to Handle Errors from Async Closures in Swift 2
Dynamic Uicollectionview Inside Dynamic Uitableviewcell
Swiftui Sheet Not Updating Variable
String Comparison in Swift Is Not Transitive
Make a Type Itself -- Not Its Instances -- Conform to a Protocol
Ibdesignable and Uitableviewcell
In Swift, Can You Find All Types in a Module That Adhere to a Specific Protocol
Is There a Technical Reason to Use Swift's Caseless Enum Instead of Real Cases
Swift and Objectmapper: Nsdate with Min Value
Using Structs (Bytes) with Swift - Struct to Nsdata and Nsdata to Struct
Crop Image According to Rectangle in Swiftui
Captureoutput Function Isn't Called Using Setsamplebufferdelegate
Why Does Using Dynamictype on a Force Unwrapped Nil Optional Value Type Work
Need Detailed Explanation for Memoize Implementation in Swift (Wwdc 14, Session 404)