Padding zeros in a function


I am using a slider to generate numbers from 0 to 150. I need all numbers to be generated with preceeding zeros if they are less than 3 digits. So 10 would be 010, 8 would be 008,100 remains unchanged. I am sure there is a way to accomplish this in a function but I cannot find a suitable example. Can someone give me a hand?



Can be achieved with the new ES8 feature / function named "padstart" in a function node:

msg.payload = "8".padStart(3, "0");
return msg;





I am a bit of a pedant (which is a good thing for those developing with computers) so I have to point out that to ask for a Number in javascript to have leading zeros does not make sense. A number is a number. I think probably what you are asking is how to convert a number to a string representing the number and with leading zeros. Thus the number 10 would be converted to the string "010". If that is the case then @Andrei's result may well be the right way to go. Note though that generally you should do this at the point you display it, keep it as a number in the rest of the flow. If you are using a dashboard node to display the value you can do the formatting in the node itself by using


in the Value Format field. For example:

1 Like


Or, of course, even better