admin管理员组

文章数量:1304225

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?

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?

Share Improve this question edited Nov 13, 2015 at 10:49 mitbal asked Nov 13, 2015 at 10:30 mitbalmitbal 3556 silver badges15 bronze badges 2
  • NumberLong values are essentially "long integers" or 64-bit integers. There is no ponent to be "rounded down" as you claim. The response is likely a Double instead. You basically need to show what you are actually doing and sample data and result for a reasonable question that people can reproduce here as well. Edit your question please. – Blakes Seven Commented Nov 13, 2015 at 10:33
  • See my answer below, you need to quote your numbers when creating a NumberLong otherwise they are converted to floats first: NumberLong("2517720935641120769"); – Alex Commented Nov 13, 2015 at 10:54
Add a ment  | 

2 Answers 2

Reset to default 6

Use the undocumented exactValueString property:

> NumberLong("2517720935641120769").exactValueString
2517720935641120769

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)

本文标签: javascripthow to print numberlong valueStack Overflow