點燈坊

失くすものさえない今が強くなるチャンスよ

Extracting Floating-Point Number to N Digits

Sam Xiao's Avatar 2021-12-19

As for extracting Floating-point Number to finite digit, we can use parseInt or toFixed.

Version

ECMAScript 2015

parseInt

let x = 2.432;
let y = 2.438;

parseInt (x * 100) / 100 // ?
parseInt (y * 100) / 100 // ?

Extract floating-point number to 2 digits without rounding :

  • multiply 100 and pass to parseInt
  • divide 100

float000

toFixed

let x = 2.432;
let y = 2.438;
+x.toFixed (2) // ?
+y.toFixed (2) // ?

Extract floating-point number to 2 digits with rounding :

  • Use toFixed (2) to extract 2 digit
  • Use + to convert to Number

float001

Conclusion

  • These are most often use cases for Floating-point Number