course hero when a floating point value is truncated, it is rounded.

by Dr. Josiane Nader 8 min read

What does truncating a number in the range of 4.0 mean?

Truncating a number in the range [3.0, 4.0) returns the number 3

How to truncate a positive value?

So, an easy way to truncate a positive value is to simply subtract 0.5 from it and then round it.

What is truncation?

In simplest terms, truncation means to chop off the decimal portion of a number. This means:

What is the algorithm of subtracting 0.5 from a value and then rounding it?

The algorithm of subtracting 0.5 from a value and then rounding it (which truncates a positive number) actually has so many uses that Java has been nice enough to include a method in its standard library that will do it for you.

What does subtracting 0.5 mean in Java?

Note that when you subtract 0.5, you actually write it as 0.5f. This is because Java treats any decimal constant you write into your code as type double by default, and you must include a trailing 'f' if you wish the number to be treated as type float.

What is round method in Java?

The round method is a static method in the class Math. Therefore, anytime you wish to call that method, the method name must be proceeded by the class name (ie: Math.round) Check the Java Class Documentation to see what type of values Math.round will accept as an argument and what types of values it will return.

How to round a number that is less than or equal to 5?

If the number does need to be rounded, look at the third digit after the decimal. If that digit is greater than or equal to five, add 0.01 to the number you are rounding. If the digit is less than or equal to four, do nothing. Finally, erase everything after the second digit after the decimal.