# Convert Between Percentages and Decimal

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.

• 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? – Doorknob Jul 2 '17 at 1:07
• Good point. I've updated to make it more clear that all numbers involved are floating point numbers. – musicman523 Jul 2 '17 at 1:14
• Are we allowed to use 2 languages? – ckjbgames Jul 2 '17 at 1:52
• I'm downvoting because it's a very boring challenge. Nothing wrong about the challenge itself, other than that. – isaacg Jul 2 '17 at 10:25
• @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 :) – musicman523 Jul 2 '17 at 14:39

# Mathematica, 34+20=54

to Decimal

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


to Percentage

ToString[100#]<>"%"&


# Japt, 7 bytes

From percentage:

/L


Test it online!

To percentage:

*L+'%


Test it online!

# Python 2, 59 bytes

This one does both.

lambda s:'%'in s andfloat(s[:-1])/100orfloat(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!

• Why do you need the backticks in the second snippet? Isn't returning as float allowed? – Mr. Xcoder Jul 2 '17 at 9:42
• Percentages must be taken and returned with a percent sign. – Karl Napf Jul 2 '17 at 9:54
• @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. – Mr. Xcoder Jul 2 '17 at 14:40

# Java, 45 bytes

-4 bytes thanks to musicman523.

From decimal, to percent:

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


To percent, from decimal:

a->a*100+"%"

• You sure the second function is valid Java? – LegionMammal978 Jul 2 '17 at 14:37
• @LegionMammal978 I was surprised when I tried it out. Yes, it's valid Java. – Okx Jul 2 '17 at 14:37
• @Okx would new Float(...) work in place of Float.valueOf(...)? – musicman523 Jul 3 '17 at 7:13
• @musicman523 So it would. Thanks! – Okx Jul 3 '17 at 11:27

# Perl 6, 10 + 10 = 20 bytes

Decimal to percentage:

*×100~'%'


Percentage to decimal:

*.chop/100


# Dyalog APL, 20 bytes

To percentages

'%',⍨100∘×


From percentages

.01×∘⍎¯1↓⊢


Try it online!

• You can shorten the 0.01 to .01 – Kritixi Lithos Jul 2 '17 at 5:01
• '%'~⍨⊢ can become ¯1↓⊢ – Kritixi Lithos Jul 2 '17 at 8:45
• @KritixiLithos thanks! – Uriel Jul 2 '17 at 12:05

# PHP, 62 bytes 61 bytes

Thanks @ckjbgames

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


Try it online!

• Remove the newline. That should help. – ckjbgames Jul 2 '17 at 1:49
• @ckjbgames Thanks for the tip! – kip Jul 2 '17 at 2:08
• PHP 7.1 <?=$argn[-1]>'%'?($argn*100)."%":$argn/100; – Jörg Hülsermann Jul 2 '17 at 13:11 • <?=100*$argn."%"; and <?=$argn/100; should be the shortest way form the commandline with the -F option – Jörg Hülsermann Jul 2 '17 at 14:12 # Haskell 16+19 = 35 bytes Percent to decimal: (/100).read.init  Decimal to percent: (++"%").show.(*100)  # JavaScript (ES6), 20+12=32 bytes ## To Decimal p=>parseFloat(p)/100  ## To Percentage d=>d*100+'%'  # 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 '%'  # Jelly, 5 + 5 = 10 bytes % → number ṖV÷ȷ2  Try it online! number → % ×ȷ2”%  Try it online! Full program only. # 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%  # Python 3, 8177 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. • +1 for an extremely well-made PPCG answer. Also, removing some whitespace will save you some bytes. – ckjbgames Jul 2 '17 at 1:34 • 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.) – GarethPW Jul 2 '17 at 1:50 # Python 3, 2624 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. • Write two.... – CalculatorFeline Jul 2 '17 at 1:22 • @CalculatorFeline yeah – ckjbgames Jul 2 '17 at 1:23 • Does this convert back and forth between decimal and percent? – NonlinearFruit Jul 2 '17 at 1:25 • @NonlinearFruit Need to do that – ckjbgames Jul 2 '17 at 1:26 • @NonlinearFruit How to best implement – ckjbgames Jul 2 '17 at 1:26 # Python 2, 67 bytes lambda x:float(x.strip('%'))*[100,.01]['%'in x]+['%','']['%'in x]  Try it online! • This is a really clever answer. I like it. – ckjbgames Jul 18 '17 at 13:17 # Python 3, 71 bytes i=input() print(float(i[:-1])/100if'%'in i else'%.2f%%'%(float(i)*100))  Try it online! # 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.

# 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)

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

# 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%


Decimal to percentage (21 bytes)

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


Percentage to decimal (21 bytes)

f x = read(init x)/100

• 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->. – Laikoni Jul 2 '17 at 11:58

# ,,,, 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                               []