dev.to staff

Posted on

# Daily Challenge #85 - Unwanted Dollars

If you are faced with an input box like this:

+--------------+
Enter the price of the item, in dollars: |              |
+--------------+

Do you put the dollar sign in or not? Inevitably, some people will type a dollar sign while others will leave it out. The instructions could be made clearer - but that won't stop those that don't read them.

Write a function that converts a string representing a number into the number itself. Consider negative numbers and any extraneous space characters that the user might put in. If the given string does not represent a number, return 0.0.

Sample Cases:
money_value("12.34")
money_value(" \$5.67")
money_value("-\$ 0.1")
money_value("\$-2.3456")
money_value("007")
money_value(" \$ 89")
money_value("   .11")
money_value("\$.2")
money_value("-.34")
money_value("\$\$\$")

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!

Peter

In Go!

func moneyValue(value string) float64 {
// check if negative is in the incoming string, in cases of -\$12.23
isNegative := strings.Contains(value, "-")
val, err := strconv.ParseFloat(value, 64)
for err != nil && len(value) > 0 {
value = value[1:]
val, err = strconv.ParseFloat(value, 64)
}
// catch for leading '-' placements, in cases of -\$12.23
if isNegative && val > 0 {
val = -val
}
return val
}

Go Playground

Amin

Elm (point-free style)

import String exposing (replace, toFloat)
import Maybe exposing (withDefault)

moneyValue : String -> Float
moneyValue  =
replace "\$" ""
>> replace " " ""
>> toFloat
>> withDefault 0.0

Test it online

Here.

Zohar Peled • Edited

c#:

double money_value(string input)
{
return double.TryParse(input.Replace("\$", "").Replace(" ", ""), out double result) ?
result :
0.0;
}

K.V.Harish

My solution in js

const moneyValue = (str) => isNaN(a = parseFloat(str.replace(/[^0-9.]/g, ''))) ? 0 : a;

lormayna • Edited