$toDecimal (Convert to Decimal128)
Last updated: 2026-10-09
$toDecimal (Convert to Decimal128)
$toDecimal converts a value to Decimal128, the high-precision decimal type for money and other precision-sensitive arithmetic, avoiding the binary floating-point errors of double. It accepts numbers, numeric strings and booleans; null stays null. Typical uses: accumulating and comparing order amounts. Mixed arithmetic with double auto-promotes to decimal, but invalid string conversions throw, so guard with $convert onError.
| Category | Set, Condition & Conversion |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $toDecimal: <expression> }
⚙️ Parameters
| expression | A number, a numeric string, or a boolean. |
|---|
Returns:A Decimal128 value; null when the input is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $toDecimal: parse an amount string to high precision
db.orders.aggregate([
{ $project: {
amount: { $toDecimal: '$amountStr' }
} }
])
Output:
{ '_id': 1, 'amount': { '$numberDecimal': '199.90' } }
📌 Notes
- Prefer decimal for money to avoid double precision errors
- Invalid numeric strings (e.g. 'abc') throw
- null input yields null
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhy use decimal for money?
Adouble has binary floating-point error; 0.1 accumulates imprecisely, while Decimal128 is exact.
QWhat inputs convert?
ANumbers, numeric strings, and booleans (true becomes 1).
QWhat about the string 'abc'?
AIt throws; guard with $convert onError.