Home > Back-end >  How to transform a float into the minimum float value with the same number of decimals
How to transform a float into the minimum float value with the same number of decimals

Time:11-17

I have a function that takes as input a number (either float or int) and should return the minimum value with the same digit:

   function toMinValue( n ) {
       const minValue = //...
       console.log(minValue)
       return minValue   
   }

   toMinValue(0.002) // expected 0.001
   toMinValue(0.8) // expected 0.1
   toMinValue(0.09) // expected 0.01
   toMinValue(8) // expected 1
   toMinValue(78) // expected 10

any suggestion on how to achieve that?

CodePudding user response:

That sounds like a job for logarithms!

function toMinValue( n ) {
    const minValue = 10 ** Math.floor(Math.log10(n))
    console.log(minValue)
    return minValue   
}

toMinValue(0.002) // expected 0.001
toMinValue(0.8) // expected 0.1
toMinValue(0.09) // expected 0.01
toMinValue(8) // expected 1
toMinValue(78) // expected 10

Taking the log base b of a number basically means asking how many digits do we need to write it in base b. So we need a log base 10, floor it to get an integer, then "undo" the log by raising 10 to that power.

  • Related