MCPcopy Index your code
hub / github.com/gavv/httpexpect / AsNumber

Method AsNumber

string.go:1103–1193  ·  view source on GitHub ↗

AsNumber parses float from string and returns a new Number instance with result. If base is 10 or omitted, uses strconv.ParseFloat. Otherwise, uses strconv.ParseInt or strconv.ParseUint with given base. Example: str := NewString(t, "100") str.AsNumber().IsEqual(100) Specifying base: str.AsNu

(base ...int)

Source from the content-addressed store, hash-verified

1101// str.AsNumber(10).IsEqual(100)
1102// str.AsNumber(16).IsEqual(256)
1103func (s *String) AsNumber(base ...int) *Number {
1104 opChain := s.chain.enter("AsNumber()")
1105 defer opChain.leave()
1106
1107 if opChain.failed() {
1108 return newNumber(opChain, 0)
1109 }
1110
1111 if len(base) > 1 {
1112 opChain.fail(AssertionFailure{
1113 Type: AssertUsage,
1114 Errors: []error{
1115 errors.New("unexpected multiple base arguments"),
1116 },
1117 })
1118 return newNumber(opChain, 0)
1119 }
1120
1121 b := 10
1122 if len(base) != 0 {
1123 b = base[0]
1124 }
1125
1126 var fnum float64
1127 var inum int64
1128 var unum uint64
1129 var err error
1130
1131 inum, err = strconv.ParseInt(s.value, b, 64)
1132 fnum = float64(inum)
1133
1134 if err == nil && int64(fnum) != inum {
1135 opChain.fail(AssertionFailure{
1136 Type: AssertValid,
1137 Actual: &AssertionValue{s.value},
1138 Errors: []error{
1139 errors.New("expected:" +
1140 " number can be represented as float64 without precision loss"),
1141 },
1142 })
1143 return newNumber(opChain, 0)
1144 }
1145
1146 if err != nil && errors.Is(err, strconv.ErrRange) {
1147 unum, err = strconv.ParseUint(s.value, b, 64)
1148 fnum = float64(unum)
1149
1150 if err == nil && uint64(fnum) != unum {
1151 opChain.fail(AssertionFailure{
1152 Type: AssertValid,
1153 Actual: &AssertionValue{s.value},
1154 Errors: []error{
1155 errors.New("expected:" +
1156 " number can be represented as float64 without precision loss"),
1157 },
1158 })
1159 return newNumber(opChain, 0)
1160 }

Callers 5

TestString_AliasFunction · 0.95
TestString_AsNumberFunction · 0.95
NumberMethod · 0.95
TestString_FailedChainFunction · 0.80
TestE2EReport_ValuesFunction · 0.80

Calls 6

newNumberFunction · 0.85
enterMethod · 0.80
leaveMethod · 0.80
failedMethod · 0.80
failMethod · 0.80
ErrorfMethod · 0.65

Tested by 4

TestString_AliasFunction · 0.76
TestString_AsNumberFunction · 0.76
TestString_FailedChainFunction · 0.64
TestE2EReport_ValuesFunction · 0.64