package converter import "errors" import "fmt" import "strconv" import "strings" const ( markerMiles = "mi" markerKm = "km" markerFeet = "ft" markerMeter = "m" MilesToKm float64 = 1.609344 FeetsToMeters float64 = 3.28084 ) var ( inUnit string inVal float64 asMeter float64 err error convVal float64 ) func Convert(input, convTo string) (string, error) { switch { case strings.HasSuffix(input, markerKm): inUnit = markerKm case strings.HasSuffix(input, markerFeet): inUnit = markerFeet case strings.HasSuffix(input, markerMeter): inUnit = markerMeter case strings.HasSuffix(input, markerMiles): inUnit = markerMiles default: return "", errors.New("Invalid input: " + input) } inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64) if err != nil { return "", errors.New("Invalid input number (" + err.Error() + ")") } switch inUnit { case markerMiles: asMeter = inVal * MilesToKm * 1000 case markerKm: asMeter = inVal * 1000 case markerFeet: asMeter = inVal * FeetsToMeters case markerMeter: asMeter = inVal } switch convTo { case markerMiles: convVal = asMeter / (MilesToKm * 1000) case markerKm: convVal = asMeter / 1000 case markerFeet: convVal = asMeter / FeetsToMeters case markerMeter: convVal = asMeter default: return "", errors.New("Invalid unit: " + convTo) } return fmt.Sprintf("%.2f%s", convVal, convTo), nil }