Tuesday, June 17, 2014

Lots of Money

I was working building out some Project Venice data structures, specifically money, when it occurred to me that an Integer value would not be enough.  It would only allow players to have ~2 billion bucks (  2,147,483,647 exactly).  While that is more than enough for the prototype, I figured I better solve that issue now by moving to 64bit integers.  That will give us a max value of 9,223,372,036,854,775,808.  I think that should be enough :) 

Javascript does not really support 64bit numbers, which will make doing things like addition and subtracting difficult.   By default, mongoose ( the ORM adapter I am using for MongoDb ) also does not support a 64bit integer data type  Luckily, there is a workaround with mongoose-long.  So I went ahead and added that to my package.json file then did a npm install ( or you can do npm install mongoose-long).

Next, I adjusted my database schema and added:   money:mongoose.Schema.Types.Long

Now you can pass in really large numbers to the money field, hooray!  We're not quite done yet though.  The Long datatype is actually made up of a few fields and looks like this:  money: { _bsontype: 'Long', low_: 1942892530, high_: 2874 }.  That's not very useful, so we need to use toString() on it to get it to display as a readable number again.

If you are not using Mongoose, I'd suggest node-bigint.  It is pretty to use:  

var m = '1000000000000';
var lotsofmoney = bigint(m).add(10).toString();

With these options, Project Venice now supports a whole lot of money.  What will you do with it all?  Well, that will be the fun part :)