开发者

Strings or Floats?

I have a list of product edition se开发者_C百科rial numbers to store in MongoDB, eg,

[{"name": "123 > Item A", "serial_number": "123.1"},
 {"name": "123 > Item B", "serial_number": "123.2"},
 {"name": "123 > Item C", "serial_number": "123.3"},
 {"name": "123 > Item D", "serial_number": "123.4"},
 {"name": "124 > Item A", "serial_number": "124.1"}]

Should I use floats for strings for the serial_number property?


Use strings. If you use floats, it is likely that you will have rounding errors. So you will get numbers like 123.30000001 instead of 123.3.


It is also possible you may have serial numbers that are not totally numeric or which start with leading zeros. Serial number is not something you want to ever do math with so it should be stored as string data just like postal codes and phone numbers. These are identifier numbers, not numbers used in mathmatics and thus they really are string data just like name is.

Actually I almost never use float for anything as it is an inexact datatype and it's bad for things you want to do calculations on and wht's the point of a a number that you can;t accurately do calculations on?


Yeah. I def would use strings. It is possible that you're serial number is not representable as a float, so it wouldn't be exactly right.

For things that have to be accurate i.e. serial numbers, money, etc. it's suggested that you never use floats.


Not unless you're OK with your serial numbers being unrepresentable in floating point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜