1

I get an error on typescript using Snyk Code Quality:

Performing multiplication on a string (from calling toFixed) and a number (from number literal 10) will trigger an implicit coercion of the operands to number. If this is intended, consider making the coercion explicit.

Here's a sample snippet of my code:

function(numberValue: number) { // this is a number is a parameter that is called
 // sample numberValue passed on is 1.23
 const roundNumber = Math.floor(Number(numberValue.toFixed(1)) * 10) / 10;
 console.log(roundNumber); // if sample numberValue is 1.23 then this displays 1.2
}
naveen
  • 53,448
  • 46
  • 161
  • 251
ebanster
  • 886
  • 1
  • 12
  • 29
  • I dont know why the error is thrown. But `Math.floor(Number(numberValue.toFixed(1)) * 10) / 10` is same as `Number(numberValue.toFixed(1))` AFAIK – naveen Aug 15 '22 at 11:47
  • @naveen `Math.floor(x * n) / n` is an easy way to round (or rather, floor) to the nearest `n` from `x`. – kelsny Aug 15 '22 at 19:47
  • @kelly: after toFixed(1)? – naveen Aug 15 '22 at 19:48
  • @naveen `x` would be `Number(numberValue.toFixed(1))` in `Math.floor(x * n) / n`, where n is 10. Try a few values for `x` and `n` yourself to see that it does floor to the nearest `n` from `x`. – kelsny Aug 15 '22 at 19:50

1 Answers1

1

In my test today, the issue is not showing. This may be due to Snyks engine receiving improvements.

If you still see it, I would recommend to open a support ticket. :)

The code may be simplified a bit, as others have mentioned:

export function convert(numberValue: number): string {
    // this is a number is a parameter that is called
    // sample numberValue passed on is 1.23
    const roundNumber = Math.floor(numberValue * 10) / 10

    // if sample numberValue is 1.23 then this returns 1.2
    return roundNumber.toString()
}
Sebastian Roth
  • 11,344
  • 14
  • 61
  • 110