Padding zeros in a function

#1

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?

0 Likes

#2

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

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

Results:

"008"

0 Likes

#3

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

{{("000"+msg.payload.toString()).slice(-3)}}

in the Value Format field. For example:

[{"id":"db73c0d3.6c81f8","type":"ui_text","z":"6dc690a3.1abc88","group":"90837d20.135ef","order":0,"width":0,"height":0,"name":"","label":"padded","format":"{{(\"000\"+msg.payload.toString()).slice(-3)}}","layout":"row-spread","x":361.5,"y":399,"wires":[]},{"id":"4b0c11c8.19b34","type":"inject","z":"6dc690a3.1abc88","name":"","topic":"","payload":"27","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":144.5,"y":397,"wires":[["db73c0d3.6c81f8"]]},{"id":"4b8f17ff.727fb8","type":"inject","z":"6dc690a3.1abc88","name":"","topic":"","payload":"10","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":146,"y":469,"wires":[["db73c0d3.6c81f8"]]},{"id":"90837d20.135ef","type":"ui_group","z":"","name":"Default","tab":"bbb172bf.44157","disp":false,"width":"6","collapse":false},{"id":"bbb172bf.44157","type":"ui_tab","z":"","name":"Home","icon":"dashboard"}]
1 Like

#4

Or, of course, even better

{{msg.payload.toString().padStart(3,"0")}}
0 Likes