Round Double to 3 Points Decimal

Limiting double to 3 decimal places

Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878

EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

Round double to 3 points decimal

A common trick is to do it with math:

value = std::round(value * 1000.0) / 1000.0;

This scales the value, applies ordinary rounding and then scales it back. You may have some precision loss as is typical with floating-point math, and this won't be effective at extreme ranges of what can be represented by double, but often it's "good enough".

For something more generalized, put this in a function that accepts rounding to any amount:

double round_to(double value, double precision = 1.0)
{
return std::round(value / precision) * precision;
}

Example:

#include <cmath>
#include <iostream>

double round_to(double value, double precision = 1.0)
{
return std::round(value / precision) * precision;
}

int main()
{
double value = 10.0078;
double precision[] = { 0.001, 0.01, 0.1, 1, 2, 3, 4 };
for (double p : precision)
{
double result = round_to(value, p);
std::cout << "round_to(" << value << ", " << p << ") = " << result << "\n";
}
}

Output:

round_to(10.0078, 0.001) = 10.008
round_to(10.0078, 0.01) = 10.01
round_to(10.0078, 0.1) = 10
round_to(10.0078, 1) = 10
round_to(10.0078, 2) = 10
round_to(10.0078, 3) = 9
round_to(10.0078, 4) = 12

How to round a number to n decimal places in Java

Use setRoundingMode, set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output.

Example:

DecimalFormat df = new DecimalFormat("#.####");
df.setRoundingMode(RoundingMode.CEILING);
for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) {
Double d = n.doubleValue();
System.out.println(df.format(d));
}

gives the output:

12
123.1235
0.23
0.1
2341234.2125

EDIT: The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value:

Double d = n.doubleValue() + 1e-6;

To round down, subtract the accuracy.

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 to round value to only 3 decimal points?

Math.Round(per, 3)

However, you've two logical errors in your approach. You are using double to deal with amounts of money and percentages applied to it.

double is appropriate for use with natural things in the real world, like the length of your nose, or the number of seconds between a celebrity being arrested and a joke about it appearing on Twitter.

Money and percentage discounts are not natural things, but artificial amounts based on particular numbering systems.

Almost all of these are decimal based, except for Mauritanian ouguiyas, Malagasy ariaries, and the Maltese scudo, and several obsolete currencies (like the old British pound, shillings and pence). Of the three used in current times, the first two are base-5 based (and so representable without error in a decimal system) and the last is pegged to the Euro, so there's no need to worry about it.

Now, when we deal with the real world we get problems because our numbering system is in a particular base, and so we get results like 0.33333333333333333333333333333.

With money, we can only get these mistakes with division, because unless we divide, nothing will force a base-limit error upon us.

But double doesn't use decimal internally, it uses binary. Binary has different numbers that result in recurrent digits after the point. E.g. 0.1 and 0.01. Most of the time the rounding errors involved will cancel out, but sometimes they won't.

Hence, when dealing with money, always use decimal rather than double unless you've a very good reason (if you can't explain why the above doesn't apply to your case, then you don't).

The second problem is that since you're doing percentages, you are doing division, and so you will still get some rounding errors.

The solution is to store one more decimal places than you need. E.g. if you want to be accurate to 3 decimal places (as you say) then store 4.

For example, if at some point we divided 12 by 7 and rounded to three points, we'd have 1.714. If we then multiplied by 7 again, we'd have 11.998. If however we'd stored the four-decimal 1.7143 and only displayed 1.714, then multiplying by 7 again would give us 12.0001 which we'd display (rounding to 3 places again) as 12.

We can't avoid rounding errors, but we can work at a higher precision until the latest moment necessary, so the rounding errors are themselves lost to rounding.

Math.Round number with 3 decimal

See: Math.Round Method (Double, Int32)

Because of the loss of precision that can result from representing
decimal values as floating-point numbers or performing arithmetic
operations on floating-point values, in some cases the Round(Double,
Int32) method may not appear to round midpoint values to the nearest
even value in the digits decimal position. This is illustrated in the
following example, where 2.135 is rounded to 2.13 instead of 2.14.
This occurs because internally the method multiplies value by
10digits, and the multiplication operation in this case suffers from a
loss of precision.

And the example is:

   public static void Main()
{
double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
foreach (double value in values)
Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));

}

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 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"


Related Topics



Leave a reply



Submit