DEV Community

dev.to staff
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!

Top comments (9)

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

const discoverOriginalPrice = (price, discount) => (price*100/(100-discount)).toFixed(2);
Enter fullscreen mode Exit fullscreen mode

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

Collapse
 
choroba profile image
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';
Collapse
 
smz_68 profile image
Ardalan

im not so familier with perl but i like it.

Collapse
 
scrabill profile image
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
Collapse
 
juanrodriguezarc profile image
Juan Rodríguez
DiscoverOriginalPrice = (price, disc) => Math.round(price/((100 - disc)/100) * 100) / 100 
Collapse
 
brightone profile image
Oleksii Filonenko

Elixir:

defmodule Price do
  def original(price, discount),
    do: Float.round(price * 100 / (100 - discount), 2)
end
Collapse
 
kvharish profile image
K.V.Harish

My solution in js

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

Handles 100% discount 😉

Collapse
 
matrossuch profile image
Mat-R-Such

Python

def DiscoverOriginalPrice(new_price, discount):
    return '%.2fM' %((new_price*100)/(100-discount))
Collapse
 
devparkk profile image
Dev Prakash