Skip to content

Enhance DecimalField: Add optional rounding support to to_representation()Add optional rounding logic to DecimalField serialization #9737

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

DarshanRedddy
Copy link

Summary

This PR introduces support for optional decimal rounding in the DecimalField serializer field. By adding a rounding parameter, developers can now control how decimal values are quantized during serialization — such as rounding up, down, or to the nearest value.


Motivation

Controlling decimal precision is crucial in real-world APIs that handle:

  • 💸 Financial calculations (e.g., prices, taxes, discounts)
  • 📏 Measurement tools (e.g., distances, weights)
  • 📊 Scientific data and reports

While DecimalField enforces digit and decimal precision, it lacked direct control over the rounding mode. This enhancement improves the flexibility and precision of API responses for such use cases.


What's Changed

  • 🔧 Added a new rounding parameter to DecimalField.__init__()
  • 🧮 Applied rounding logic in to_representation() using Python's Decimal.quantize()
  • 🔒 Added validation to ensure rounding is one of the decimal.ROUND_* constants
  • ✅ Added a dedicated unit test in tests/test_fields.py to verify rounding behavior (e.g., ROUND_HALF_UP)

Example Usage

from decimal import ROUND_HALF_UP

price = serializers.DecimalField(
    max_digits=6,
    decimal_places=2,
    rounding=ROUND_HALF_UP
)

---

## Backward CompatibilityThe new parameter is **optional**If `rounding` is not provided, existing behavior is unchangedFully backward-compatible with all existing serializers

---

## Testing

- All core DRF tests pass using `pytest`  
- Custom test added for rounding behavior in `tests/test_fields.py`

---

## Additional Notes

- Contribution aligns with DRFs goal of being a flexible, production-grade API toolkit  
- This feature has real-world demand across finance, commerce, and analytics

---

Please let me know if any changes or enhancements are needed!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy