I have five digit US zip codes coming out of the database. When JavaScript see them, it treats them as a number and lops off the leading zeros.
How do I get JavaScript t开发者_如何学Goo treat the numbers as a string so that they display correctly?
Quote them.
In both JavaScript and JSON 05123
is an octal number equal to 2643
(thanks @Marc B) and "05123"
is a string containing only numeric characters.
Don't quote them in your database, of course. You'll want to quote them in the JavaScript or JSON you are generating in the server-side code that's reading the information from the database and passing it to your client-side code. Ordinarily, that's as simple as casting the zip code to a string (or, as is the more likely case, not casting your numeric zips to a number.)
Here's a function which pads a number until it's 5 characters long.
function formatzip(num) {
var s = "00000"+num;
return s.substr(s.length-5);
}
But really the zip code should never have turned into a number in the first place. It should be a string when you set it's value to begin with.
I'm sure that String()
would probably work. If by that time, the 0s are already lopped off, you could do something like:
zip = <Source>;
zip = String(zip);
while(zip.length<5){
zip = "0" + zip;
}
Tell me if this isn't what you're looking for.
A guess... Some genius decided to store ZIP codes in a numeric column type inside the database (NUMBER
, INT
or whatever type your DBMS implements). If that was the case, all ZIP codes that start with zero are already corrupted.
It'd be better to switch the column to VARCHAR
before it's too late and fix the corrupted rows manually.
精彩评论