官术网_书友最值得收藏!

Difference between integers and floats

Ruby has a few different data types for working with numbers. Two of the primary options are integer and float. In this section, we're going to walk through the difference between the two data types and how they can affect your program. In the previous section, Arithmetic order of operations, you saw a little bit of strange behavior when it came to division. I'm going to bring up the same example. In the code, the division equation, 2 / 216 was treated as 0. We know this is obviously not true, so why did Ruby return this value?

When it saw the values 2 and 216, it treated them as integers. So, it assumed that the user would want a rounded value, so it rounded it to the nearest whole number, which is 0 in this case.

To get the correct answer, we'll need to convert it into a decimal, which will automatically give us a float data type. So, if you run 2.0 / 216, you will get the answer as 0.00925925925925925925925925925926.

This is the difference between the integer and float data types in Ruby. In a real-world application, you are more likely to use the float data type in your database as opposed to integers because you can get more accurate values. In fact, I rarely use integer data type in a real-world application because I want precise values to work with when I'm working with calculations.

Integers are okay to use for items such as an ID; however, make sure to only use them when you know you're not going to be performing calculations with the value.

In general, there are three main number-based data types in Ruby:

  • Integer (for example, 1, 2, and 3)
  • Float (for example, 1.2, 3.1, and 4.23)
  • Decimal (for example, 3.56456456456 and 3.456588990)

The main difference between float and decimal is that the latter gives a more accurate value, even though it is likely to take up more space in your database. This is why decimal is ideal for complex financial applications.

I hope this gives you a clear understanding of the different numerical data types in Ruby.

主站蜘蛛池模板: 奇台县| 交口县| 临猗县| 江西省| 长乐市| 晋宁县| 花莲市| 新沂市| 娄底市| 乐亭县| 巧家县| 额尔古纳市| 肇庆市| 土默特左旗| 江北区| 平顶山市| 寿阳县| 白河县| 禹州市| 麟游县| 铜鼓县| 义乌市| 米泉市| 睢宁县| 通榆县| 庄河市| 浦东新区| 镇康县| 成都市| 盘山县| 正安县| 云和县| 梅州市| 昆山市| 凤凰县| 丹阳市| 鄂尔多斯市| 宝兴县| 突泉县| 玛曲县| 西乌珠穆沁旗|