If you're faced with an input box, like this:
+--------------+
Enter the price of the item, in dollars: | |
+--------------+
Do you put the $ sign in, or not? Inevitably, some people will type a $ sign and others will leave it out. The instructions could be made clearer - but that won't help those people who never read instructions anyway.
A better solution is to write code that can handle the input whether it includes a $ sign or not.
So, write a simple function that converts a string representing a number into the number itself. Your function should be able to handle negatives!
Examples:
money_value("12.34") => 12.34
money_value("-0.89") => -0.89
money_value(" .11") => 0.11
money_value("007") => 7
Tests:
money_value("-$ 0.1")
money_value("12.34")
money_value("$-2.3456")
money_value("$.2")
Good luck!
This challenge comes from geoffp on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (20)
This is my solution in Python3
EDIT: Removed space, thanks for correcting me guys
This was great, but failed (Python 3.8) the first test due to the added space - added an additional replace and passed all tests.
You could also use the method
strip
strip
doc:This doesn't work with string = "-$ 0.1" isn't it? I'd rather prefer the replace way :P
Thank you!
you alse need to remove space from the string to avoid the exception
This is my solution in javascript:
A more readable version:
My solution in Typescript
I like this but I will do it without /g as you will encounter this replacement at the most once. Also space after $ maybe present or may not be so
/\$?\s?/
would do I guess. What do you think?In C with O(1):
Is
atof
O(1)?Well, technically
atof
is O(n), but while specifing the big O notation, I just abstracted all the library calls to O(1). And I think that doing this is the most stupid thing but it just helps me to analyse what could be the worst case scenario of my implementation. Hope it doesn't mislead any wrong information.Here's Kotlin with a String extension function:
Ruby
APL (using Dyalog APL):
(Use the bookmarklet on this post to see the code with APL font and syntax highlighting.)
Removes the characters
$
and space using "set difference"~
, and evaluates⍎
the resulting string as APL expression. The preceding-
gets evaluated as the "negate" function, and APL's numeric notation uses¯
(read "high minus") for the negative sign.This was my solution typescript/javascript
Here is the simple solution with Python:
Using the
while
loop andif...else
conditions to check specific string pattern and replace unwanted character.Then return
s
with casting to float value finally.solution in js
Javascript
fails on negative values, due to replacing the '-'