0

I am trying to make a calculator of sorts where you perform an operation and the code returns an answer that follows the rules of significant figures. Here is a boiled down portion of what I have coded:

var x = 0.002.toString().split(""); //to convert the number to a list

for(i = 0; i <= x.length; i++) {
  if(x[i] != 0 || ".") {
    x.splice(0, i);
    { break; }
  }
}

The for loop is supposed to delete all of the non-significant 0's at the beginning, but it isn't working and I don't know what the problem could be.

iAmOren
  • 2,760
  • 2
  • 11
  • 23
  • I don't think `toString()` ever returns insignificant zeroes. – Robo Robok Oct 19 '20 at 22:39
  • `split` "converts" to an Array, not a list... – iAmOren Oct 19 '20 at 23:01
  • A significant figure is concept used in science to represent the accuracy of data. For the number 0.002, the only significant figure is the 2, so I am trying to get rid of the zeros so I have only significant figures left. Hopefully, I will be able to substitute the 0.002 with any other number less than 1 and greater than 0. – Keaden Knight Oct 19 '20 at 23:02
  • Why did you surround `break;` with `{` and `}`? – iAmOren Oct 19 '20 at 23:02
  • I'd add braces to make sure `(x[i] != 0 || ".")` tests exactly what I want - unless you are an expert on operator precedences... Also, to not have to re-think - either you in the future, or anyone reading your code, including me/us. – iAmOren Oct 19 '20 at 23:04
  • You are looping with condition length and you are changing it in the loop = very iffy... You are splicing `i`, are you sure you didn't mean `1`? How about using `shift`? – iAmOren Oct 19 '20 at 23:08
  • I don't know what the `{}` do for the `break;`, that's just how I saw it on W3schools – Keaden Knight Oct 19 '20 at 23:12
  • Do you want one digit or from that one until the end? "0.00257" => "2" or "257"? `(0.00257).toString().replace(/^[0.]*/g,"").charAt(0)` or `(0.00257).toString().replace(/^[0.]*/g,"")`. – iAmOren Oct 19 '20 at 23:28
  • I would want the 257, what does the code you wrote do? – Keaden Knight Oct 20 '20 at 00:06

1 Answers1

0
 if( x[i] != 0 || ".")

always succeeds because "." is always truthy. Try

if( !(x[i] === '0' || x[i] === '.')  )

to check if the character is neither a zero nor decimal point.

traktor
  • 17,588
  • 4
  • 32
  • 53