# How to convert a float into a desired precision, then convert it to bigdecimal? (correct way?)

**URL:** <https://forum.crystal-lang.org/t/how-to-convert-a-float-into-a-desired-precision-then-convert-it-to-bigdecimal-correct-way/4846>\
**Category:** Help & Support\
**Created:** [August 11, 2022, 11:45am UTC](https://forum.crystal-lang.org/t/how-to-convert-a-float-into-a-desired-precision-then-convert-it-to-bigdecimal-correct-way/4846 "2022-08-11T11:45:50Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![zw963](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/zw963/32/1623_2.png) [@zw963](https://forum.crystal-lang.org/u/zw963)\
**Post date:** [August 11, 2022, 11:45am UTC](https://forum.crystal-lang.org/t/how-to-convert-a-float-into-a-desired-precision-then-convert-it-to-bigdecimal-correct-way/4846/1 "2022-08-11T11:45:50Z")

</div>

Following is a example:

```crystal
require "big"

x = 100/20.45
p! x # 4.88997555012225
p! typeof(x) # Float64

x1 = sprintf("%.2f", x)
p! x1 # 4.89
p! typeof(x1) # String

x2 = BigDecimal.new(x1)
p! x2 # => 4.89
p! typeof(x2) # BigDecimal

```

I guess there maybe a better solution?

---

<div class="post-metadata">

**Author:** ![straight-shoota](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/straight-shoota/32/36_2.png) [@straight-shoota](https://forum.crystal-lang.org/u/straight-shoota)\
**Post date:** [August 11, 2022, 12:55pm UTC](https://forum.crystal-lang.org/t/how-to-convert-a-float-into-a-desired-precision-then-convert-it-to-bigdecimal-correct-way/4846/2 "2022-08-11T12:55:27Z")

</div>

Yeah, there’s no need to go through string for this. You can just use [`Number#round`](https://crystal-lang.org/api/1.5.0/Number.html#round%28digits%3ANumber%2Cbase%3D10%2C%2A%2Cmode%3ARoundingMode%3D%3Aties_even%29-instance-method) to round the value.  
I’d recommend converting to `BigDecimal` first and then round that big decimal, though. This avoids any surprises with floating point precision.

```nohighlight
require "big"
x = 100 / 20.45
x.to_big_d.round(2) # => 4.89

```

---

<div class="post-metadata">

**Author:** ![zw963](https://yyz2.discourse-cdn.com/flex036/user_avatar/forum.crystal-lang.org/zw963/32/1623_2.png) [@zw963](https://forum.crystal-lang.org/u/zw963)\
**Post date:** [August 11, 2022, 1:18pm UTC](https://forum.crystal-lang.org/t/how-to-convert-a-float-into-a-desired-precision-then-convert-it-to-bigdecimal-correct-way/4846/3 "2022-08-11T13:18:49Z")

</div>

Oops, i miss those methods defined in superclass Number …

Thank you.
