Jscript formatting numbers? - Printable Version -Shoutbox (https://shoutbox.menthix.net) +-- Forum: MsgHelp Archive (/forumdisplay.php?fid=58) +--- Forum: Messenger Plus! for Live Messenger (/forumdisplay.php?fid=4) +---- Forum: Scripting (/forumdisplay.php?fid=39) +----- Thread: Jscript formatting numbers? (/showthread.php?tid=66300) Jscript formatting numbers? by Robin4286 on 09-16-2006 at 01:22 AM okay, so say i have a variable named bob. Bob is equal to 1. Is there a way i can make it so that it displays bob as 01, sort of like toPrecision, but it adds zeroes before the number? RE: Jscript formatting numbers? by CookieRevised on 09-16-2006 at 02:18 AM
You need to create your own function for this as something like that doesn't exist in JScript (eg: like the Format() function in VB6). There are many ways to do it and what you will use mostly depends on your 'precision' and on your personal preferences. code:though not really interesting if your precision is, let say, 7 digits. Because then you need something like: code:This can be shortened by using a loop (this also prevents the constant conversion that JScript needs to do between strings and numbers): code:However, loops can be slow, especially when adding strings together. Though, in these cases I would assume you wouldn't want to add 1000 zero's in front of it so speed shouldn't be much of an issue. However, another method which does not uses a loop would be something like: code:But just as with the loop, you can have the problem that if Bob is lower than 100000, Bob will be a string and when it is higher than 999999 it will be a number. But in practice the difference between a number and a string shouldn't be noticeable in most cases though. So you could disregard the next methods actually. But just for your information, here are the methods where Bob will always be converted to a string, even if there isn't a leading zero added: code:This will always return a string, regardless of the length of Bob. Yet another solution for this (with the loop): code:This will again always return a string, even if Bob has 7 or more digits. -- So, all the above methods can be used even for numbers which have more digits than the amount of leading zeros you can add. If you explicitly know that your number will never be larger than the amount of digits you whish to represent, you can use even a very short 'trick' to add leading zeros: code: |