skip to Main Content

I want to calculate some percentage that is creating values 0.0034657, 0.000002376876868, 0.00004557600 etc. like this bt in my react project i want to round the ablove values and print those values 0.0034, 0.0000023, 0.000045 like this. Can please someone tell me logic for this or any arithmatic functions for this.

Values : 0.0034657, 0.000002376876868, 0.00002357600
Expected output : 0.0034, 0.0000023, 0.000023

2

Answers


  1. I think you can use the toFixed method

    like this:

    const roundToDecimal = (value, decimalPlaces) => {
       const rounded = Number(value).toFixed(decimalPlaces);
       return Number(rounded)
    }
    
    const values = [0.0034657, 0.000002376876868, 0.00002357600];
    
    const roundedValues = values.map(value => roundToDecimal(value, 4))
    
    console.log(roundedValues);
    
    const roundToDecimal = (value, decimalPlaces) => {
       const rounded = Number(value).toFixed(decimalPlaces);
       return Number(rounded)
    }
    
    const values = [0.0034657, 0.000002376876868, 0.00002357600];
    
    const roundedValues = values.map(value => roundToDecimal(value, 4))
    
    console.log(roundedValues);
    Login or Signup to reply.
  2. Here’s a generalised solution, you can pass in any number as the second argument

    Haven’t tested with negative values – deal with that yourself if you need to

    Added it for you :p

    const special = (v, n = 2) => {
        const s = Math.sign(v);
        if (!s) {
            return 0;
        }
        const digits = 10 ** ((n - 1) - Math.floor(Math.log10(s * v)));
        return s * Math.floor(s * v * digits)/digits;
    }
    console.log([0, 0.0034657, 0.000002376876868, 0.00002357600, -0.00002357600].map(v => special(v)));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search