fix float2int()
Costa Tsaousis (ktsaou) committed
Jan 23, 2016 at 13:51 UTC
28f70b99f183caa7ebd8f55ea95d9997dd3a9003
1 file changed
+24
-12
plugins.d/charts.d.plugin
+24
-12
@@ -239,32 +239,44 @@ fixid() {
239
# to integer, give a multiplier
240
# the result is stored in ${FLOAT2INT_RESULT}
241
# so that no fork is necessary
242
+# the multiplier must be a power of 10
243
float2int() {
244
local f="$1" m="$2" a b l
245
245
- # echo >&2 "f='${f}', m='${m}'"
246
+ #echo >&2 "f='${f}', m='${m}'"
247
+
248
+ # the length of the multiplier - 1
249
+ l=$[ ${#m} - 1 ]
250
251
# split the floating point number
252
# in integer (a) and decimal (b)
253
a=${f/.*/}
254
b=${f/*./}
255
252
- # the length of the multiplier
253
- l=$[ ${#m} - 1 ]
254
-
255
- # cut the decimal part if it is
256
- # longer than the multiplier
257
- [ ${#b} -gt ${l} ] && b=${b:0:${l}}
258
- b=$[10#$b]
259
-
260
- # prepend a zero to the integer
261
- # part, if it is missing
256
+ # prepend a zero to the integer part
257
+ # if it is missing
258
[ -z "${a}" ] && a="0"
259
+ # strip leading zeros - base 10 convertion
260
a=$[10#$a]
261
262
+ # check the length of the decimal part
263
+ # against the length of the multiplier
264
+ if [ ${#b} -gt ${l} ]
265
+ then
266
+ # too many digits - take the most significant
267
+ b=${b:0:${l}}
268
+ elif [ ${#b} -lt ${l} ]
269
+ then
270
+ # too few digits - pad with zero on the right
271
+ local z="00000000000000000000000" r=$[l - ${#b}]
272
+ b="${b}${z:0:${r}}"
273
+ fi
274
+ # strip leading zeros - base 10 convertion
275
+ b=$[10#$b]
276
+
277
# store the result
278
FLOAT2INT_RESULT=$[ (a * m) + b ]
267
- # echo >&2 "FLOAT2INT_RESULT='${FLOAT2INT_RESULT}'"
279
+ #echo >&2 "FLOAT2INT_RESULT='${FLOAT2INT_RESULT}'"
280
}
281
282