0
export function calculateDiff(first, second){

  const firstNum = Number(first);
  const secondNum = Number(second);

  return isNaN(firstNum) || isNaN(secondNum) || firstNum === 0 ? '' : firstNum - secondNum
}

// In spec test file

it('calculateDiff', () =>{
    expect(calculateDiff('',1.2)).toBe('') //PASSES as expected
    expect(calculateDiff(100.2399, 99.2455)).toBe(0.9944); //FAILS -result is 0.9943999999999988
    expect(calculateDiff(100.2399, 99.2455)).toBe(0.9943999999999988); //PASSES 
}); 

 

How can I prevent it from making this conversion? I like Number rather than parsefloat function because of the way it does Nan and handles others values.

Joe Pass
  • 1
  • 1
  • Note that there's no point in calling *any* function to convert the numbers to numbers, because they start off as numbers. You're seeing normal behavior of binary floating-point. – Pointy Mar 24 '21 at 14:47
  • the parameters could be strings too, so I do need to call Number function to determine whether it's a NaN or not. Am I missing something? example: expect('a', 1).toBe('') – Joe Pass Mar 24 '21 at 15:04
  • That's fine then, it doesn't hurt. `Number(foo)` will do the same thing as `+foo`. The `parseFloat()` function is probably the least good idea, as it will ignore trailing "garbage" (non-numeric) content in the source string. However, a number is a number in JavaScript (except for recently-introduced "big integer" values). – Pointy Mar 24 '21 at 15:09
  • But it does hurt. I don't want my result to be approximated to 0.9943999999999988 when it should be 0.9944 – Joe Pass Mar 24 '21 at 15:14
  • There's nothing you can do about that. Binary floating point behaves that way, and the linked question has extensive explanations about the topic. – Pointy Mar 24 '21 at 15:31
  • 1
    I think my mistake here is to think that Number function has something to do with it. It does not. It's all floating point problem. Simple subtraction would show the same issue. Linked question does help. Thanks. – Joe Pass Mar 24 '21 at 17:34

0 Answers0