How to round up a float to it's .99 representation?

For example:

5.09, changed to 5.99

29.56, changed to 29.99

34.64, changed to 34.99


I only have access to the current discounted price, and it’s discount percentage (integer). I’m trying to calculate it’s base price as well on the fly for my own records.

Here’s what I’ve tried:

base_price = discounted_price + discounted_percentage / 100 * discounted_price
base_price = Float.ceil(base_price, 2)

Which gives me data like:

%{
  base_price: 19.94,
  discounted_percentage: 5,
  discounted_price: 18.99,
  has_discount: true,
  platforms: ["Mac", "PC"],
  title: "Crusader Kings II: Holy Fury"
}
%{
  base_price: 29.56,
  discounted_percentage: 12,
  discounted_price: 26.39,
  has_discount: true,
  platforms: ["Mac", "PC"],
  title: "Project Highrise: Architect's Edition"
}
%{
  base_price: 5.86,
  discounted_percentage: 15,
  discounted_price: 5.09,
  has_discount: true,
  platforms: ["PC"],
  title: "Galactic Civilizations III - Heroes of Star Control: Origins (DLC)"
}

Thinking about it, I could round up to the nearest integer and then subtract x - 0.01 :thinking:

1 Like

Rounding up the nearest integer should work fine.

However, I feel compelled to note that you should not be using floats for anything dealing with currency because they can be very imprecise in certain scenarios. Instead you should be using a library like ex_money

4 Likes

Yeah I would use something like that for more complicated scenarios. In this case the number is a simple display, not really meant to intense calculations or really any calculations.


Here’s what ended up solving my use case:

base_price = discounted_price + discounted_percentage / 100 * discounted_price
base_price = Float.ceil(base_price) - 0.01
1 Like

I think your math is wrong:

discounted_price = base_price * (100 - discounted_percentage)/100

and therefore:

base_price = discounted_price * 100 / (100 - discounted_percentage)

Which gets you the correct base_price, just by rounding to 2 decimal places.

2 Likes