auto-calculate bytes to a more readable unit (like KB, MB, GB, etc.)

CarlosA84304391
Tera Contributor

I need to auto-calculate bytes to a more readable unit (like KB, MB, GB, etc.) through a ServiceNow catalog item variable.  I have 2 variable input and output.  Utilizing script below, but when testing nothing is happening in the output variable.

1st Variable: Type = Single Line Text, Question = INPUT BYTES VALUE, Name = input_bytes_value

2nd Varaible: Type = Single Line Text, Question = CONVERTED VALUE, Name = converted_value

 

SCRIPT

Applies on a catalog item view

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === '') {
        return;
    }

    // Convert bytes to a readable format
    var bytes = parseInt(newValue, 10);
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) {
        g_form.setValue('converted_value', '0 Bytes');
        return;
    }
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    var convertedSize = (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];

    // Set the converted value to the variable
    g_form.setValue('converted_value', convertedSize);
}

 

 

1 ACCEPTED SOLUTION

Chaitanya ILCR
Kilo Patron

Hi @CarlosA84304391 ,

Your script is working I have tried it in my pdi

just check if you there any errors in the console

you have this on change client script on the input_bytes_value variable only right? if no update the variable name on the catalog client script to input_bytes_value

 

 

Please mark my answer as helpful/correct if it resolves your query.

Regards,
Chaitanya

View solution in original post

2 REPLIES 2

Chaitanya ILCR
Kilo Patron

Hi @CarlosA84304391 ,

Your script is working I have tried it in my pdi

just check if you there any errors in the console

you have this on change client script on the input_bytes_value variable only right? if no update the variable name on the catalog client script to input_bytes_value

 

 

Please mark my answer as helpful/correct if it resolves your query.

Regards,
Chaitanya

CarlosA84304391
Tera Contributor

Thank you.  I was missing the value in the "Variable name" field of my script.   Sometimes you need another pair of eyes.