2
\$\begingroup\$

I, uh....honestly can't believe we don't have this one yet.

Challenge

Write two functions or programs that:

  1. Convert from decimal to percentage
  2. Convert from percentage to decimal

You may also write a single program that does both of the above.

Format

Percentages must be taken and returned with a percent sign. (In many languages, this means they will be strings.) They may be integers or floating point numbers.

Decimals are just floating point numbers.

You do not need to handle rounding errors involving very large or very small floating point numbers.

In cases where the numbers are integers (such as 56.0) you may return 56, 56., or 56.0. (This is intended to make I/O more flexible.)

Test Cases

    0.0% <-> 0.0
  100.0% <-> 1.0
   56.0% <-> 0.56
  123.0% <-> 1.23
  -11.0% <-> -0.11
-214.91% <-> -2.1491

Scoring

This is , so the shortest answer in each language wins. If you write two separate programs, add their sizes for your score.

\$\endgroup\$
13
  • 1
    \$\begingroup\$ If I'm interpreting the test cases correctly, they mandate that an input of 0.0 return both 0% and 0.0%. Which one is it? \$\endgroup\$
    – Doorknob
    Commented Jul 2, 2017 at 1:07
  • 4
    \$\begingroup\$ Good point. I've updated to make it more clear that all numbers involved are floating point numbers. \$\endgroup\$ Commented Jul 2, 2017 at 1:14
  • 3
    \$\begingroup\$ Are we allowed to use 2 languages? \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:52
  • 5
    \$\begingroup\$ I'm downvoting because it's a very boring challenge. Nothing wrong about the challenge itself, other than that. \$\endgroup\$
    – isaacg
    Commented Jul 2, 2017 at 10:25
  • 3
    \$\begingroup\$ @isaacg That's fine, and you are of course entitled to that opinion. I made this challenge knowing it wouldn't be difficult, simply because I wanted to see the answers and it's easier for new PPCG members to get involved on easier questions. Think of it as a learning opportunity - go answer in a language you've never used before! Or go answer some harder challenges if you're still not convinced :) \$\endgroup\$ Commented Jul 2, 2017 at 14:39

21 Answers 21

4
\$\begingroup\$

Mathematica, 34+20=54

to Decimal

ToExpression@StringDrop[#,-1]/100&

to Percentage

ToString[100#]<>"%"&
\$\endgroup\$
3
\$\begingroup\$

Japt, 7 bytes

From percentage:

/L

Test it online!

To percentage:

*L+'%

Test it online!

\$\endgroup\$
3
\$\begingroup\$

Python 2, 59 bytes

This one does both.

lambda s:'%'in s and`float(s[:-1])/100`or`float(s)*100`+'%'

Try it online!

Single functions, score 27 + 28 = 55

Decimal to percent, 27 bytes

lambda s:`float(s)*100`+'%'

Try it online!

Percent to decimal, 28 bytes

lambda s:`float(s[:-1])/100`

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Why do you need the backticks in the second snippet? Isn't returning as float allowed? \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 2, 2017 at 9:42
  • 1
    \$\begingroup\$ Percentages must be taken and returned with a percent sign. \$\endgroup\$
    – Karl Napf
    Commented Jul 2, 2017 at 9:54
  • 1
    \$\begingroup\$ @KarlNapf Yes, they do. But for float(s[:-1])/100 you do not need a percent sign, and hence can be returned as a floating-point number. \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 2, 2017 at 14:40
3
\$\begingroup\$

Java, 45 bytes

-4 bytes thanks to musicman523.

From decimal, to percent:

a->new Float(a.split("%")[0])/100

To percent, from decimal:

a->a*100+"%"
\$\endgroup\$
4
  • \$\begingroup\$ You sure the second function is valid Java? \$\endgroup\$ Commented Jul 2, 2017 at 14:37
  • \$\begingroup\$ @LegionMammal978 I was surprised when I tried it out. Yes, it's valid Java. \$\endgroup\$
    – Okx
    Commented Jul 2, 2017 at 14:37
  • \$\begingroup\$ @Okx would new Float(...) work in place of Float.valueOf(...)? \$\endgroup\$ Commented Jul 3, 2017 at 7:13
  • \$\begingroup\$ @musicman523 So it would. Thanks! \$\endgroup\$
    – Okx
    Commented Jul 3, 2017 at 11:27
2
\$\begingroup\$

Perl 6, 10 + 10 = 20 bytes

Decimal to percentage:

*×100~'%'

Percentage to decimal:

*.chop/100
\$\endgroup\$
2
\$\begingroup\$

Dyalog APL, 20 bytes

To percentages

'%',⍨100∘×

From percentages

.01×∘⍎¯1↓⊢

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You can shorten the 0.01 to .01 \$\endgroup\$
    – user41805
    Commented Jul 2, 2017 at 5:01
  • 1
    \$\begingroup\$ '%'~⍨⊢ can become ¯1↓⊢ \$\endgroup\$
    – user41805
    Commented Jul 2, 2017 at 8:45
  • \$\begingroup\$ @KritixiLithos thanks! \$\endgroup\$
    – Uriel
    Commented Jul 2, 2017 at 12:05
1
\$\begingroup\$

PHP, 62 bytes 61 bytes

Thanks @ckjbgames

$i=readline();echo strstr($i,'%')?(float)$i/100:($i*100).'%';

Try it online!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Remove the newline. That should help. \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:49
  • \$\begingroup\$ @ckjbgames Thanks for the tip! \$\endgroup\$
    – kip
    Commented Jul 2, 2017 at 2:08
  • \$\begingroup\$ PHP 7.1 <?=$argn[-1]>'%'?($argn*100)."%":$argn/100; \$\endgroup\$ Commented Jul 2, 2017 at 13:11
  • \$\begingroup\$ <?=100*$argn."%"; and <?=$argn/100; should be the shortest way form the commandline with the -F option \$\endgroup\$ Commented Jul 2, 2017 at 14:12
1
\$\begingroup\$

Haskell 16+19 = 35 bytes

Percent to decimal:

(/100).read.init

Decimal to percent:

(++"%").show.(*100)
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 20+12=32 bytes

To Decimal

p=>parseFloat(p)/100

To Percentage

d=>d*100+'%'
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 8 bytes

From % to decimal

¨т/

Try it online!

And from decimal to %

т*'%«

Try it online!

Explanations

¨т/
¨   # Cut of last character
 т/ # Divide by 100 (I know. Very creative)

 т*'%«
 т*    # Multiply by 100
   '%« # Append '%'
\$\endgroup\$
1
\$\begingroup\$

Jelly, 5 + 5 = 10 bytes

% → number

ṖV÷ȷ2

Try it online!

number → %

×ȷ2”%

Try it online!

Full program only.

\$\endgroup\$
1
\$\begingroup\$

Excel, 15 + 4 = 19 bytes

Assuming that the values to be converted are stored in field A1

Percentage to decimal

=NUMBERVALUE(A1)

Decimal to percentage

=A1%
\$\endgroup\$
1
\$\begingroup\$

Python 3, 81 77 74 bytes

def a(m):e=m.strip("%");f=float(e);return f/100if e!=m else str(f*100)+"%"

Try it online!

EDIT: Saved 4 bytes by removing some whitespace.
EDIT: Saved another 3 bytes by setting float(e) to a variable.

\$\endgroup\$
2
  • \$\begingroup\$ +1 for an extremely well-made PPCG answer. Also, removing some whitespace will save you some bytes. \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:34
  • \$\begingroup\$ Here's an even shorter Python 3.6 version: def a(m):e=m.strip("%");f=float(e);return f"{f*100}%"if e!=m else.01*f. Replace f"{f*100}%" with str(f*100)+"%" to make it <3.6 compatible. (The 3.6 version won't work on tio.run so use something like repl.it instead.) \$\endgroup\$
    – Gareth
    Commented Jul 2, 2017 at 1:50
0
\$\begingroup\$

Python 3, 26 24 23 bytes + 27 bytes = 50 bytes

First program (% -> decimal)

float(input()[:-1])*.01

Second program (decimal -> %):

str(float(input())*100)+'%'

Rather similar to the other one. Pretty easy, too.

\$\endgroup\$
16
  • \$\begingroup\$ Write two.... \$\endgroup\$ Commented Jul 2, 2017 at 1:22
  • \$\begingroup\$ @CalculatorFeline yeah \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:23
  • \$\begingroup\$ Does this convert back and forth between decimal and percent? \$\endgroup\$ Commented Jul 2, 2017 at 1:25
  • \$\begingroup\$ @NonlinearFruit Need to do that \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:26
  • \$\begingroup\$ @NonlinearFruit How to best implement \$\endgroup\$
    – ckjbgames
    Commented Jul 2, 2017 at 1:26
0
\$\begingroup\$

Python 2, 67 bytes

lambda x:`float(x.strip('%'))*[100,.01]['%'in x]`+['%','']['%'in x]

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ This is a really clever answer. I like it. \$\endgroup\$
    – ckjbgames
    Commented Jul 18, 2017 at 13:17
0
\$\begingroup\$

Python 3, 71 bytes

i=input()
print(float(i[:-1])/100if'%'in i else'%.2f%%'%(float(i)*100))

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Retina, 77 bytes

^-?
$&00
\b%?$
00%$&
\.(..)
$1.
(....)\.(.*)%%
.$1$2
^(-?)0+\B|\B0+(%?)$
$1$2

Try it online! Link includes test cases. Requires and returns input with at least one digit before and after the decimal point. Explanation: The first stage inserts two leading zeros after any sign, while the second stage inserts two trailing zeros and a % sign before any % sign. (The \b is needed to stop the pattern matching twice for percentages.) The third stage then multiplies by 100. This results in the correct numerical value for floats converted into percentages, but percentages are now 10,000 times too big and now have a duplicated % sign, so the fourth stage corrects this. The final stage then trims leading and/or trailing zeros as necessary.

\$\endgroup\$
0
\$\begingroup\$

ES6, 34 bytes

n=>1/n?n*100+'%':n.slice(0,-1)/100

(Now works with 0.0 and 0%)

Try it online!

This works because 1/n is NaN if a "%" is present and NaN is like false.

(1/n with n = 0 is Infinity (not NaN) and Infinity is not considered false by JS)

\$\endgroup\$
4
  • \$\begingroup\$ But !0 is also false... using 1/n might work though. \$\endgroup\$
    – Neil
    Commented Jul 2, 2017 at 9:02
  • \$\begingroup\$ I made a mistake in my original comment on why this works, !NaN is true not false. \$\endgroup\$
    – 2ndAttmt
    Commented Jul 2, 2017 at 9:10
  • \$\begingroup\$ Sorry, !0 is true too of course. What was I thinking? \$\endgroup\$
    – Neil
    Commented Jul 2, 2017 at 9:17
  • \$\begingroup\$ @Neil Thank you for your help, the new version is still 34 bytes, but now works with zero. \$\endgroup\$
    – 2ndAttmt
    Commented Jul 2, 2017 at 9:28
0
\$\begingroup\$

perl 5: 24 bytes

From % to decimal: 8 bytes (7 + 1 for p flag)

$_/=100

Usage:

echo '-214.91%' | perl -pe '$_/=100'

Output:

-2.1491

From decimal to %: 16 bytes (15 + 1 for p flag)

$_*=100;$_.="%"

Usage:

echo -2.1491 | perl -pe '$_*=100;$_.="%"'

Output:

-214.91%
\$\endgroup\$
0
\$\begingroup\$

Haskell, 60 42 bytes

Decimal to percentage (21 bytes)

f x = show(x*100)++"%"

Percentage to decimal (21 bytes)

f x = read(init x)/100
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to PPCG! As per community consensus submissions may not assume the input is present in a certain variable. Function submissions are allowed though, so you can fix your answer by prepending f x= or \x->. \$\endgroup\$
    – Laikoni
    Commented Jul 2, 2017 at 11:58
0
\$\begingroup\$

,,,, score 19

Percent to decimal, 10 bytes

-1⇆⊣f100⇆÷

Explanation

Take 56.0% for example.

-1⇆⊣f100⇆÷

               implicit input                               ["56.0%"]
-1             push -1                                      ["56.0%", -1]
  ⇆            switch "56.0%" and -1                        [-1, "56.0%"]
   ⊣           pop -1 and "56.0%" and push "56.0"           ["56.0"]
    f          pop "56.0" and push 56.0 (convert to float)  [56.0]
     100       push 100                                     [56.0, 100]
        ⇆      switch 56.0 and 100                          [100, 56.0]
         ÷     pop 100 and 56.0 and push 56.0 / 100         [0.56]
               implicit output                              []

Decimal to percent, 9 bytes

100×s'%⇆+

Explanation

Take 0.56 for example.

100×s'%⇆+

               implicitly take input and convert to float    [0.56]
100            push 100                                      [0.56, 100]
   ×           pop 0.56 and 100 and push 100 * 0.56          [56.0]
    s          pop 56.0 and push "56.0" (convert to string)  ["56.0"]
     '%        push "%"                                      ["56.0", "%"]
       ⇆       switch "56.0" and "%"                         ["%", "56.0"]
        +      pop "%" and "56.0" and push "56.0%"           ["56.0%"]
               implicit output                               []
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.