views:

58

answers:

4
+1  Q: 

Strings or Floats?

I have a list of product edition serial 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?

A: 

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.

smoore
A: 

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

Mike Daniels
+6  A: 

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.

Robert Harvey
+2  A: 

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?

HLGEM
If you're careful, and mindful of the precision issues, you can prforma accurate math calculations with them. Floating point numbers have a larger range than, say, the `decimal` type in .NET, and sometimes that additional range is necessary.
Robert Harvey