go-examples/converter/converter.go

69 lines
1.4 KiB
Go
Raw Permalink Normal View History

2017-07-09 08:28:56 +00:00
package converter
2017-07-07 12:29:36 +00:00
2017-07-09 08:48:34 +00:00
import "errors"
2017-07-07 12:29:36 +00:00
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
)
2017-07-09 08:48:34 +00:00
func Convert(input, convTo string) (string, error) {
2017-07-07 12:29:36 +00:00
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:
2017-07-09 08:48:34 +00:00
return "", errors.New("Invalid input: " + input)
2017-07-07 12:29:36 +00:00
}
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
if err != nil {
2017-07-09 08:48:34 +00:00
return "", errors.New("Invalid input number (" + err.Error() + ")")
2017-07-07 12:29:36 +00:00
}
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:
2017-07-09 08:48:34 +00:00
return "", errors.New("Invalid unit: " + convTo)
2017-07-07 12:29:36 +00:00
}
2017-07-09 08:28:56 +00:00
2017-07-09 08:48:34 +00:00
return fmt.Sprintf("%.2f%s", convVal, convTo), nil
2017-07-07 12:29:36 +00:00
}