Как округлить число в java

от admin

Округление чисел в Java

Числа с плавающей точкой (float, double) применяются при вычислении выражений, в которых требуется точность до десятичного знака. Высокая точность часто нужна в бухгалтерских и других вычислительных операциях. Но всегда ли нам нужен длинный “хвост” чисел после запятой? Может нам достаточно точности в три знака вещественной части? И есть нас такой вариант устраивает, как правильно выполнить округление? Именно об этом мы сегодня и поговорим: рассмотрим способы округления чисел в Java .

String format

Округление чисел в Java - 2

В качестве первого способа мы рассмотрим округление double: В результате мы отформатируем наше число с плавающей запятой 34766674 с точностью до 3 десятичных разрядов , так как в инструкции для форматирования мы указали три знака после запятой «%.3f. В свою очередь %f при форматировании строки обозначает тип чисел с плавающей запятой, которое включает в себя тип данных double и float в Java. В примере выше мы выводили полученное значение в консоль. Теперь вопрос: как бы можно было это сократить? Все просто: нужно использовать printf, который в свою очередь является format + print. В итоге предыдущий пример у нас сократился бы до: У экземпляра out класса PrintStream помимо этого метода есть ещё метод format, который работает аналогично: Округление происходит по режиму HALF_UP — в сторону числа, которое ближе к обрезаемому (к 0 или 10). Если же эти числа равноудалены (в случае с 5), то округление выполняется в большую сторону. Пример: Более подробно режимы округления мы разберем чуть ниже.

DecimalFormat

Math.ceil() округляет до ближайшего целого числа вверх, но отдаёт не целочисленный тип, а double:

Даже если у нас будет 34.0000000, все равно после использования Math.ceil мы получим 35,0.

Math.floor() округляет до ближайшего целого вниз, также результатом отдаёт double:

Опять же, даже если у нас будет значение 34.999999999, то после использования Math.floor мы получим 34,0.

Math.round () — округляет до ближайшего целого числа, как результат отдаёт int:

Если у нас число 34.5, округление выполняется до 35, если же чуть чуть меньше 34.499, число обрезается до 34.

Чтобы не просто обрезать всю вещественную часть, а регулировать этот процесс до определенного количества знаков и при этом округлять, число умножают на 10^n (10 в степени n), где n равно количеству необходимых знаков после запятой. После этого применяют какой-нибудь метод класса Math для округления, ну а затем снова делят на 10^n:

Class Math

Unlike some of the numeric methods of class StrictMath , all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.

By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math .

The quality of implementation specifications concern two properties, accuracy of the returned result and monotonicity of the method. Accuracy of the floating-point Math methods is measured in terms of ulps, units in the last place. For a given floating-point format, an ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value. When discussing the accuracy of a method as a whole rather than at a specific argument, the number of ulps cited is for the worst-case error at any argument. If a method always has an error less than 0.5 ulps, the method always returns the floating-point number nearest the exact result; such a method is correctly rounded. A correctly rounded method is generally the best a floating-point approximation can be; however, it is impractical for many floating-point methods to be correctly rounded. Instead, for the Math class, a larger error bound of 1 or 2 ulps is allowed for certain methods. Informally, with a 1 ulp error bound, when the exact result is a representable number, the exact result should be returned as the computed result; otherwise, either of the two floating-point values which bracket the exact result may be returned. For exact results large in magnitude, one of the endpoints of the bracket may be infinite. Besides accuracy at individual arguments, maintaining proper relations between the method at different arguments is also important. Therefore, most methods with more than 0.5 ulp errors are required to be semi-monotonic: whenever the mathematical function is non-decreasing, so is the floating-point approximation, likewise, whenever the mathematical function is non-increasing, so is the floating-point approximation. Not all approximations that have 1 ulp accuracy will automatically meet the monotonicity requirements.

Читать:
Скорость линии прием и передача 100 100 mbps как изменить

The platform uses signed two’s complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods addExact , subtractExact , multiplyExact , toIntExact , incrementExact , decrementExact and negateExact throw an ArithmeticException when the results overflow. For the arithmetic operations divide and absolute value, overflow occurs only with a specific minimum or maximum value and should be checked against the minimum or maximum as appropriate.

Округление дробных чисел до целых

Какие существуют в Java стандартные средства для округления чисел?

  • Пример округления: 3.49 — 3, 3.50 — 4, 3.51 — 4.
  1. Math.ceil(n) — возвращает наименьшее целое число, которое больше или равно аргумента n.
  2. Math.floor(n) — возвращает наибольшее целое число, которое меньше или равно аргументу n.
  3. Math.round(n) — возвращает целое число, ближайшее к аргументу n (округляет n).

Umed's user avatar

В годы моей юности, когда не было таких умных методов round/ceil/floor , округление делали примерно так:

Метод Math.round() в Java возвращает long или int (целое число), ближайшее к вещественному числу, double или float , аргумента. Иными словами — осуществляет округление до целых чисел.

MihailPw's user avatar

Тень's user avatar

вот правильный код:

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Как округлить число в java

The java.lang.Math.round() is a built-in math function which returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result after adding 1/2, and casting the result to type long.

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Syntax:

Returns:
The method returns the value of the argument rounded to the nearest int value.

Похожие статьи