go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.41k stars 1.3k forks source link

added support for float in oneof - issue #1105 #1116

Closed alirezakazemeini closed 1 year ago

alirezakazemeini commented 1 year ago

Based on the given issue, the func isOneOf(fl FieldLevel) function handles various data types including strings, integers, and floats. However, it seems like there is an issue with floats containing fractional parts.

To modify the code and make it support float values without fractions, you can update the decimal2String function to round the float value instead of throwing a panic when there is a fractional part. Here's an updated version of the function:

func decimal2String(f float64) string {
    rounded := math.Round(f)
    return strconv.FormatFloat(rounded, 'f', 0, 64)
}

or you can use it inline like:

v = strconv.FormatFloat(math.Round(field.Float()), 'f', 0, 64)

By using the math.Round function, the float value will be rounded to the nearest integer. This way, when converting the float to a string, you'll have the desired behavior of supporting float values without fractional parts.

coveralls commented 1 year ago

Coverage Status

coverage: 73.975% (+0.003%) from 73.972% when pulling db53d0284d5c2136c38db68f6354ca37f36c9590 on alirezakazemeini:issue-1105-oneof_float_support into bd1113d5c1901c5205fc0a7af031a11268ff13ee on go-playground:master.