How to realize truncation and rounding of Java data
This article mainly introduces the Java data truncation and rounding how to achieve the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that after reading this Java data truncation and rounding how to achieve the article will have a harvest, let's take a look.
When you convert float or double to an integer value, you always truncate that number, as in the following example:
Public class CastingNumbers {public static void main (String [] args) {double above = 0.7 above = 0.4; float fabove = 0.7f, fbelow = 0.4f; System.out.println ("(int) above:" + (int) above); System.out.println ("(int) below:" + (int) below); System.out.println ("(int) fabove:" + (int) fabove) System.out.println ("(int) fbelow:" + (int) fbelow);}}
Output:
(int) above: 0 (int) below: 0 (int) fabove: 0 (int) fbelow: 0
If you want to get rounded results, you need to use the round () method in java.lang.Math:
Public class RoundingNumbers {public static void main (String [] args) {double above = 0.7 above = 0.4; float fabove = 0.7f, fbelow = 0.4f; System.out.println ("Math.round (above):" + Math.round (above)); System.out.println ("Math.round (below):" + Math.round (below)) System.out.println ("Math.round (fabove):" + Math.round (fabove)); System.out.println ("Math.round (fbelow):" + Math.round (fbelow));}}
Output:
Math.round (above): 1 Math.round (below): 0 Math.round (fabove): 1 Math.round (fbelow): 0
Because round () is part of java.lang, no additional import is required to use it.
This is the end of the article on "how to achieve truncation and rounding of Java data". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to achieve truncation and rounding of Java data". If you want to learn more knowledge, you are welcome to follow the industry information channel.