mitbal
mitbal

Reputation: 355

how to print numberlong value?

So, I tried to print a NumberLong to console from a mongoshell. However, when I casted the NumberLong variable into string, the value got rounded down. After initial search, it looks like it happens because the precision limit of javascript float. Here is one example in mongoshell:

var abc = NumberLong(2517720935641120769);
print(abc);

The output is

NumberLong("2517720935641120769")

However, when I tried to cast it into string to just print the value

print(''+abc);

The output is

2517720935641121000

Is there any trick to print the value inside NumberLong?

Upvotes: 5

Views: 6347

Answers (2)

Florent Guillaume
Florent Guillaume

Reputation: 8367

Use the undocumented exactValueString property:

> NumberLong("2517720935641120769").exactValueString
2517720935641120769

Upvotes: 6

Alex
Alex

Reputation: 21766

Make sure you quote the number when creating a NumberLong field. If you do not quote your value it will be cast to a float and you will loose precision.

NumberLong(123123123123131123).toString()
>>NumberLong("123123123123131120")

However, if you quote your value it will be correctly stored and returned:

NumberLong("123123123123131123").toString()
>>NumberLong("123123123123131123")

Both statements have been executed directly in the MongoShell, the value after >> gives the output returned by the MongoShell (version 3.0.7)

Upvotes: 1

Related Questions