0

I got a question.

My backend recieve number string from frontend.

The important point is, I want to cut number at the second demical point.

ex1) '2.346' => 2.34

ex2) '2.3' => 2.3

ex3) '4.246' => 4.24

ex4) '4.1' => 4.1

And when I try this code with '2.346' or '4.246'

let v = '2.346'

v = parseInt(v * 100) / 100

console.log(v)
// v = 2.34

But when I try this code with 2.3 or 4.1, it makes wierd...

let v = '2.3'

v = parseInt(v * 100) / 100

console.log(v)
// v = 2.29

what is the problem in my code...?

Haetal
  • 11
  • 3
  • You are a victim of the fact that floating point numbers do not have infinite precision. You cannot actually represent certain numbers as floating point numbers. – Sumner Evans Jan 24 '21 at 06:05

2 Answers2

1

Floating-point precision means that multiplying and then dividing by the same number like with your parseInt(v * 100) / 100 may sometimes have long trailing insignificant digits that weren't there to begin with.

If I were you, I'd use a regular expression to match up to 2 digits past a . instead:

const clean = str => str.match(/\d+(?:\.\d{1,2})?/)[0];

console.log(clean('2.346'));
console.log(clean('2.3'));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

function tofixed(str){
  return parseInt(str * 1000 / 10) /100
}

console.log(tofixed("2.346"))
console.log(tofixed("2.3"))
console.log(tofixed("4.246"))
console.log(tofixed("4.1"))
  • 1
    Can you please add a description on why this is different than `parseInt(v * 100) / 100`? – adiga Jan 24 '21 at 06:38
  • @adiga `"2.3" * 100 = 229.99999999999997` and please see https://0.30000000000000004.com/ `"2.3" * 1000 / 10 = 230` – Javad Shariati Jan 24 '21 at 07:01
  • Just FYI man. This will fail with a very large number. E.g. `tofixed('53219247129812312132.453')` – codemonkey Jan 24 '21 at 07:34
  • @JavadShariati I'm aware of [floating point](https://stackoverflow.com/questions/588004/is-floating-point-math-broken). What about `parseInt(str * 1000 / 10) /100` fixes the issue that `parseInt(str * 100) / 100` doesn't? While the code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – adiga Jan 24 '21 at 08:02
  • @adiga `parseInt(str * 1000 / 10) /100` `===` `parseInt((str * 1000) / 10) /100`. @codemonkey thanks . `str.match(/\d+(?:\.\d{1,2})?/)[0]` is best result. ;) – Javad Shariati Jan 24 '21 at 17:10