$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.

CategorySet, Condition & Conversion
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $toDecimal: <expression> }

⚙️ Parameters

expressionA 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏