Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 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}]
  2.  
  3. function bestNotation(num_g, min_scale, max_scale) {
  4.     var exp = 0
  5.     var result = num_g
  6.     while(result >= 10 && 10**exp < max_scale) {
  7.         result /= 10
  8.         exp++
  9.     }
  10.     while(result < 1 && 10**exp > min_scale) {
  11.         result *= 10
  12.         exp--
  13.     }
  14.  
  15.     unit_object = scales.find(x => x.scale === 10**exp)
  16.     return result + ' ' + unit_object.unit
  17. }
  18.  
  19. // Risultati testati
  20. // bestNotation(1284, 0.001, 1000) -> "1.284 kg"
  21. // bestNotation(0.052, 0.001, 1000) -> "5.2 cg"
  22. // bestNotation(250000, 0.001, 1000) -> "250 kg"
  23. // bestNotation(0.000000001, 0.001, 1000) -> "0.000001 mg"
  24. // bestNotation(5.3, 0.001, 1000) -> "5.3 g"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement