skip to Main Content

Suppose a value is "floored" (floored in some arbitrary digit) when its displayed (7.785->7.7, 110.6->110). Let this floored value be called flooredTarget. Suppose I have another number variable named toCheck. How would I check if the significant digits of flooredTarget and toCheck are equal?

NOTE: the first parameter is flooredTarget.

checkSignificant(7.7, 7.785); // true as 7.7 is common
checkSignificant(7.785, 7.8); // false as toCheck doesn't contain 7.785

Should I just check if toCheck.toString().beginsWith(flooredTarget.toString())? Or is there some other better way (Assume any language)

2

Answers


  1. You can use regexp

    function checkSignificant(flooredTarget, toCheck) {
      const [digits] = flooredTarget.toString().match(/(?<=.)d+/)
      return new RegExp(`(?<=\.)${digits}`).test(toCheck.toString())
    }
    
    console.log(checkSignificant(7.7, 7.785));
    console.log(checkSignificant(7.785, 7.8));
    Login or Signup to reply.
  2. Converting to text is a performance killer there are other ways for example I see it like this in C++:

    //---------------------------------------------------------------------------
    double align_to_exp(double x,int e) // align number x so its most significant digit is at 10^e weight
        {
        bool sig=false;
        if (x==0.0) return 0.0;         // special case
        if (x<0.0){ sig=true; x=-x; }   // ignore sign
        x*=pow(10,e-floor(log10(x)));   // shift digit positions to 10^e
        if (sig) x=-x;                  // restore sign
        return x;
        }
    //---------------------------------------------------------------------------
    int count_equal_digits(double a,double b) // return number of common significant digits between a,b or -1 if both are zero
        {
        int i;
        double aa,bb;
        a=align_to_exp(fabs(a),0);      // align numbers to 10^0
        b=align_to_exp(fabs(b),0);
        if ((a==0.0)&&(b==0.0)) return -1;  // special case
        for (i=0;i<17;i++)              // limit to 17 digits for double
            {
            aa=floor(a);                // aa is compared digit
            bb=floor(b);                // bb is compared digit
            if ((aa!=bb)||(a==0.0)||(b==0.0)) break;    // stop on difference
            a-=aa; a*=10.0;             // move to next digit
            b-=bb; b*=10.0;             // move to next digit
            }
        return i;
        }
    //---------------------------------------------------------------------------
    

    there is still a lot of room for improvement like making align_to_exp brunchless but In this form the code is more understandable.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search