skip to Main Content

Here is my easy code. I want to the two function get different result, but the global variable precision passed is the pointer. So it get same result for two function.

precision = 4
func = (value) => value.toFixed(precision)
precision = 2
func2 = (value) => value.toFixed(precision)
console.log(func(2.3333))
console.log(func2(2.3333))

Can anyone tell me how to use the value of precision instead of itself? Then the two function should return different result.

2

Answers


  1. To use a different value for precision for each function call, pass the precision as function argument. This will eliminate the need for a second function:

    const fixedNumber = (value, precision) => value.toFixed(precision);
    
    console.log(fixedNumber(2.333, 2));
    console.log(fixedNumber(2.333, 3));

    As can be seen from the output of your example, set function will read the value when it is called and not when it was defined.

    Login or Signup to reply.
  2. You could take a closure over precision and get a function for the value.

    const
        fix = precision => value => value.toFixed(precision),
        fix4 = fix(4),
        fix2 = fix(2);
    
    console.log(fix2(2.3333));
    console.log(fix4(2.3333));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search