0

Help write in Javascript laconically. Already сhecked number (9 characters; 0 < Foo < 100) needs to be rounded to two SIGNIFICANT digits after the dot. That is, all empty digits (digit='0') after the dot must be saved, and the next two digits must be saved. Round off the rest (rather than discard). And if there is an integer part - just round up to hundredths.

0.123456 -> 0.12
0.023456 -> 0.023
0.003456 -> 0.0035
0.000456 -> 0.00046
21.000456 -> 21
21.019999 -> 21.2
mamadu
  • 13
  • 2
  • A significant digit rounding can be done with `const arr=[0.123456,0.023456,0.003456,0.000456,21.000456,21.019999]; arr.forEach((v,f)=>{ f=10**-Math.ceil(Math.log10(v)); console.log(v,Math.round(v*f)/f); })` - but this will not work for your requirement for numbers between 1 and 100 to have a maximum of two fractional digits. – Carsten Massmann Jun 18 '22 at 08:23
  • @Carsten Massmann, Yes, it works. I came here to post my solution, but it turned out that you answered me. `iRound (number, digit) { if (!digit) digit = 3 let pow = -1 * Math.floor(Math.log10(number)) + Math.floor(digit) - 1 if (pow < 0) pow = 0 return Math.round(number * Math.pow(10, pow)) / Math.pow(10, pow) } }` – mamadu Aug 18 '22 at 05:45

1 Answers1

1

A significant digit rounding can be done with

const arr=[1234567,0.123456,0.023456,0.003456,0.000456,21.000456,21.019999];

function sigdig(val,dig){

    let v = Math.abs(val)
    if (v === 0) {
        return 0.00
    }

    const f=10**(-Math.ceil(Math.log10(v))+dig);
    return Math.sign(val)*(Math.round(v*f)/f);
}

arr.forEach(v=>console.log(v,sigdig(v,2))); 

console.log("or with 3 digits:");
arr.forEach(v=>console.log(v,sigdig(v,3))); 

but this will not work for your requirement for numbers between 1 and 100 to have a maximum of two fractional digits.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • This is a great answer, and was exactly what I was looking for. Thanks! P.S. I updated the function code so that it would handle 0 as well as negative numbers. – Kenn Sebesta Apr 16 '23 at 18:03
  • 1
    I left a comment in my answer, relating to the stack overflow practice of closing questions very quickly and thereby potentially blocking helpful answers. Very often these questions are not opened again. In this case the question _was_ opened again. But I would still like to express my wish that we all should generally be a bit more considerate before closing a question. – Carsten Massmann Apr 18 '23 at 17:53