Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize truncation and rounding of Java data

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report