Read the statement by Michael Teeuw here.
Convert bytes to megabytes - JSON
-
@sdetweil Thanks for the reply.
basically t.data[i].down_rate / 1024 for kilobytes
-
@mongo116 right
-
I figured this out in the end, with the help of google :) I used the JSON.parse() reviver function to take the down_rate and up_rate from the payload and divide it by 1024 (and again by 1024) to convert the bytes to megabytes. What confused me at first was I was trying to do this in the node_helper.js, which didn’t work. It needed to be in the socketNotificationReceived of the .js file.
var payload = JSON.parse(payload, function (key, value) { if ( key === 'down_rate' ) { return (value / 1024 / 1024).toFixed(2); } else if ( key === 'up_rate' ) { return (value / 1024 / 1024).toFixed(2); } else { return value; } });
I’m sure there is a proper way of doing this, but for my needs this is now working as needed.
-
@mongo116 json data before parse is called is a text string, and math in string is bad.
parse converts to number if possible
then math works.number/(1024*1024)
is parts of megabyte -
in MMM-Tools, i use this :
convert: function(octet,FixTo) { octet = Math.abs(parseInt(octet, 10)); var def = [[1, 'b'], [1024, 'Kb'], [1024*1024, 'Mb'], [1024*1024*1024, 'Gb'], [1024*1024*1024*1024, 'Tb']]; for (var i=0; i < def.length; i++) { if (octet < def[i][0]) return (octet/def[i-1][0]).toFixed(FixTo)+def[i-1][1]; } },
Syntax:
octet: octets to transform
FixTo: precision of the resultFixto precision sample: if you set it to
2
result is :X.XX
, if you set it to3
result isX.XXX
Of course, Unit is automaticaly set ! b /Kb/Mb/Mb/Tb
That’s to you to adapt if you want to use it ;) -
Thanks for the replies :thumbs_up_light_skin_tone:
I’ve got the bytes string converting to a number, so that’s all good. Now the next question, @Bugsounet how do I use your function within the JSON.parse function?
var payload = JSON.parse(payload, function (key, value) { if ( key === 'down_rate' ) { var num = Number(value); return (num/(1024*1024)).toFixed(2); }
Just to add, I had tried the following and receive a this.convert is not a function
var downrate = this.convert(value,0); return downrate;