# Issue

I am attempting to solve an edge case to a task related to a personal project.

It is to determine the unit price of a service and is made up of the `total_amount`

and `cost`

.

Examples include:

```
# 1
unit_price = 300 / 1000 # = 0.3
# 2
unit_price = 600 / 800 # = 0.75
# 3
unit_price = 500 / 1600 # = 0.3125
```

For 1 and 2, the unit_prices can stay as they are. For 3, rounding to 2 decimal places will be sufficient, e.g. `(500 / 1600).round(2)`

The issue arises when the float becomes long:

```
# 4
unit_price = 400 / 56000 # = 0.007142857142857143
```

What's apparent is that the float is rather long. Rounding to the first significant figure is the aim in such instances.

I've thought about using a regular expression to match the first non-zero decimal, or to find the length of the second part and apply some logic:

`unit_price.match ~= /[^.0]/`

`unit_price.to_s.split('.').last.size`

Any assistance would be most welcome

# Solution

One should use `BigDecimal`

for this kind of computation.

```
require 'bigdecimal'
bd = BigDecimal((400.0 / 56000).to_s)
#⇒ 0.7142857142857143e-2
bd.exponent
#⇒ -2
```

*Example:*

```
[10_000.0 / 1_000, 300.0 / 1_000, 600.0 / 800,
500.0 / 1_600, 400.0 / 56_000].
map { |bd| BigDecimal(bd.to_s) }.
map do |bd|
additional = bd.exponent >= 0 ? 0 : bd.exponent + 1
bd.round(2 - additional) # THIS
end.
map(&:to_f)
#⇒ [10.0, 0.3, 0.75, 0.31, 0.007]
```

Answered By - Aleksei Matiushkin Answer Checked By - Katrina (PHPFixing Volunteer)

## 0 Comments:

## Post a Comment

Note: Only a member of this blog may post a comment.