|
| 1 | +// Copyright 2015 MongoDB Inc. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +#include <cstdlib> |
| 16 | +#include <iostream> |
| 17 | + |
| 18 | +#include <bsoncxx/builder/stream/document.hpp> |
| 19 | +#include <bsoncxx/decimal128.hpp> |
| 20 | +#include <bsoncxx/exception/exception.hpp> |
| 21 | +#include <bsoncxx/types.hpp> |
| 22 | + |
| 23 | +using namespace bsoncxx; |
| 24 | + |
| 25 | +int main(int, char**) { |
| 26 | + // Convert a string to BSON Decimal128. |
| 27 | + decimal128 d128; |
| 28 | + try { |
| 29 | + d128 = decimal128{"1.234E+3456"}; |
| 30 | + } catch (const bsoncxx::exception& e) { |
| 31 | + // The example won't fail, but in general, arbitrary strings |
| 32 | + // might not convert properly. |
| 33 | + return EXIT_FAILURE; |
| 34 | + } |
| 35 | + |
| 36 | + // Add it to a BSON document. |
| 37 | + builder::stream::document build_doc; |
| 38 | + build_doc << "counter" << d128; |
| 39 | + auto doc = document::value{build_doc.extract()}; |
| 40 | + |
| 41 | + // Extract a BSON Decimal128 from a document view. |
| 42 | + auto view = doc.view(); |
| 43 | + auto d128copy = view["counter"].get_decimal128().value; |
| 44 | + |
| 45 | + // Convert it back to a string. |
| 46 | + std::cout << "Counter is " << d128copy.to_string() << std::endl; |
| 47 | + |
| 48 | + return EXIT_SUCCESS; |
| 49 | +} |
0 commit comments