def show @item = Item.find(params[:id]) if @item.price < 1 #price is DECIMAL type #Write some processing end end
When I check the type, it is String. Apparently Decimal is a fixed-point number type and handles more accurate values than floating-point types, so it seems that it will be returned as a character string (naturally ...?)
logger.debug(@item.price.class) -> String
It works as expected when using the BigDecimal library
require 'bigdecimal' if BigDecimal(@item.price) < 1 #Write some processing end
Floating-point types such as Float can handle a large number of digits, but errors occur because the numbers after the decimal point cannot be represented by binary numbers. → Rounding error
The fixed-point type solves this problem, but it can handle fewer digits than the floating-point type.
・ Https://docs.ruby-lang.org/ja/latest/library/bigdecimal.html ・ Https://qiita.com/jnchito/items/d0ef71b25732ad5a881c ・ Https://qiita.com/angel_p_57/items/24078ba4aa5881805ab2