tags:

views:

486

answers:

2

I'm having a bit of a go slow in the brain department today and thought maybe somone had done this before.

Given the numbers below, what simple means could I use in Javascript to work out the decimal point as a number, eg:

  • 1 = Decimal point: 0
  • 10 = Decimal point: 1
  • 1678 = Decimal point: 3
  • -0.56 = Decimal point: -1
  • -0.0045 = Decimal point: -3
+4  A: 

log(x)/log(10) // log base 10 of x

Need absolute value if you want to pass negative numbers for x.

Need floor if you want integer result.

Example:

Math.floor(Math.log(Math.abs(-0.56))/Math.log(10));

mbeckish
A: 

It's not entirely clear what your algorithm is. What makes -0.56 decimal point -1 and not -2? Similarly, does the sign of the original number matter to the sign of the decimal point?

You can take the log base 10 of the absolute value of the numbers, then truncate to the integer to get the "decimal point" and get all of the results shown above. But, there are a number of algorithms that will do so within the provided set while diverging on other numbers.

Jekke
Fair point. To give some context, its less so a matter of mathematical precision as it is working out number ranges for display purposes on the Y Axis of a dynamic chart. The decimal arrived at drives the measure of Y Axis step increments
j pimmel