SPQRInc
SPQRInc

Reputation: 198

Store integer with leading 0 (if set)

using eloquent is it possible to save a numeric value like 012345 with the leading 0 or is the only possibility to store the value as string?

To provide more details: I'd like to store a zip-code, which can have a leading 0 in Germany. There's no possibility to always add the 0, because not all zips start with 0

Upvotes: 0

Views: 1320

Answers (2)

A.A Noman
A.A Noman

Reputation: 5270

012345 is not a number. It's a string. 12345 is the number. SQL Server is able to recognize that those extra zeros are not needed to define the number, so it ignores them. If you want to dispaly a value as 012345 to the application, I'd suggest doing the formatting on the application side. That way the number stored in SQL Server is still a number if you want do addition, aggregation, or other calculations. If you really have to store it as 012345, you need to convert it to a character field; char, varchar, nvarchar, nchar.

For Details

Upvotes: 1

Junior Gantin
Junior Gantin

Reputation: 2192

Numeric datatypes do not retain leading zeros, as they are insignificant to the number you want to store. Char or Varchar is more appropriate. You could set a constraint to ensure only numeric characters are stored.

If you absolutely cannot change the data type, then another alternative is to store the number of leading zeros into another int field

So in your example you would store: Value : 32 Leading zeros : 2

Source https://stackoverflow.com/a/23309167/5442966

Upvotes: 1

Related Questions