loading...

Daily Challenge #85 - Unwanted Dollars

thepracticaldev profile image dev.to staff ・1 min read

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!

Posted on by:

thepracticaldev profile

dev.to staff

@thepracticaldev

The hardworking team behind dev.to ❤️

Discussion

markdown guide
 

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

 

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.

 

c#:

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

My solution in js

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

Hello,

Javascript version utilizing parseFloat, which by default only removes trailing garbage.

function moneyVal( value ) {
    while ( value.length && isNaN(parseFloat( value )) ) {
        value = value.substring(1);
    }
    return isNaN(parseFloat( value )) ? 0 : parseFloat( value );
}


console.log( moneyVal("US $  -34.456 $$") );

codepen.io/IngmarsLazdins/pen/eYYm...