I receive a decimal number with a maximum of 4 digits after the "." and I know this number is in milligram.
I have to find the best matching unit (milligram, gram, kilogram) for the number.
for an example if I receive
edited
116000000.0000 milligram, it's going to return 116.0000 kilogram
66990000.0000 milligram, it's going to return 66.9900 kilogram
49000010.0000 milligram, it's going to return 49000.0100 g
49000000.0100 milligram, it's going to return 49000000.0100 milligram
1001 milligram, it's going to return 1.0010 gram
1010 milligram, it's going to return 1.0100 gram
1000 milligram, it's going to return 0.0010 kilogram
1100 milligram, it's going to return 0.0011 kilogram
135005 milligram, it's going to return 135.0050 gram
and last sample 10013500 milligram, it's going to return 10.0135 kilogram
I'm currently using this code, which I think look/is ugly and can fail
Dim temp As Decimal
Dim u = New List(Of Integer)(New Integer() {1, 1000, 1000000})
For i = 0 To u.Count - 1
temp = CDec(qty / u(i))
If (temp * 10000) - Math.Truncate(temp * 10000) <> 0 AndAlso (temp * 10000) - Math.Truncate(temp * 10000) < 1 Then
temp = CDec(qty / u(i - 1))
Exit For
End If
Next
qty = temp
is there a better/nicer way of doing what I do?
edit for precision
the input can be any decimal between 0.0001 and maximum that a decimal can accept in .net
the output need to be rounded to the best unit with a maximum of 4 digits after "." without losing any precision