Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- scales = [{unit: 'g', scale: 1}, {unit: 'dag', scale: 10}, {unit: 'hg', scale: 100}, {unit: 'kg', scale: 1000}, {unit: 'mg', scale: 0.001}, {unit: 'cg', scale: 0.01}, {unit: 'dg', scale: 0.1}]
- function bestNotation(num_g, min_scale, max_scale) {
- var exp = 0
- var result = num_g
- while(result >= 10 && 10**exp < max_scale) {
- result /= 10
- exp++
- }
- while(result < 1 && 10**exp > min_scale) {
- result *= 10
- exp--
- }
- unit_object = scales.find(x => x.scale === 10**exp)
- return result + ' ' + unit_object.unit
- }
- // Risultati testati
- // bestNotation(1284, 0.001, 1000) -> "1.284 kg"
- // bestNotation(0.052, 0.001, 1000) -> "5.2 cg"
- // bestNotation(250000, 0.001, 1000) -> "250 kg"
- // bestNotation(0.000000001, 0.001, 1000) -> "0.000001 mg"
- // bestNotation(5.3, 0.001, 1000) -> "5.3 g"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement