dev.to staff

Posted on

# Daily Challenge #30 - What is the price?

Your challenge today is to find the original price of a product before sales discount.

For example:

Given an item at \$75 sale price after applying a 25% discount, the function should return the original price of that item before applying the sale percentage, which is (\$100.00) of course, rounded to two decimal places.

DiscoverOriginalPrice(75, 25) => 100.00M where 75 is the sale price (discounted price), 25 is the sale percentage and 100 is the original price

Note: The return type must be of type decimal and the number must be rounded to two decimal places.

Good luck!

This challenge comes from user ahamidou. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge for a future post? Email yo+challenge@dev.to with your suggestions!

Alvaro Montoro

JavaScript

``````const discoverOriginalPrice = (price, discount) => (price*100/(100-discount)).toFixed(2);
``````

My solution is almost the same as Juan Rodríguez's, just using `.toFixed(2)`. Link to live demo on CodePen.

E. Choroba

Perl solution with tests:

``````#!/usr/bin/perl
use warnings;
use strict;

sub original_price {
my (\$sale_price, \$discount) = @_;
sprintf '%.2f', \$sale_price / (1 - \$discount / 100)
}

use Test::More tests => 3;

is original_price(75,    25), '100.00';
is original_price(50,    50), '100.00';
is original_price(51.98, 30), '74.26';
``````

Ardalan

im not so familier with perl but i like it.

Shannon Crabill • Edited

I have figured out the logic in Ruby, but the result gets weird when it comes to perfect numbers.

``````def DiscoverOriginalPrice(sale_price, discount)
sale_percent = sale_price / (100.00 - discount)
original_price = sale_percent * 100.00
original_price.round(2)
end
``````

Which returns

``````DiscoverOriginalPrice(75,25) => 100.0 # Close, but it should be 100.00
DiscoverOriginalPrice(51.98,30) => 74.26
DiscoverOriginalPrice(50,50) => 100.0 # Close, but it should be 100.00
``````

Juan Rodríguez
``````DiscoverOriginalPrice = (price, disc) => Math.round(price/((100 - disc)/100) * 100) / 100
``````

Oleksii Filonenko

Elixir:

``````defmodule Price do
def original(price, discount),
do: Float.round(price * 100 / (100 - discount), 2)
end
``````

K.V.Harish

My solution in js

``````const discoverOriginalPrice = (salePrice, discount) => isFinite(a = (salePrice / ((100 - discount) / 100)).toFixed(2)) ? a : 0;
``````

Handles 100% discount 😉

Mat-R-Such

Python

``````def DiscoverOriginalPrice(new_price, discount):
return '%.2fM' %((new_price*100)/(100-discount))
``````

Dev Prakash