0

I want to take 2 digits after float like below example:

function cut() {

var num1=8.844

// should be return 8.84

var num2=8.847

// should be return 8.84
}
Bence László
  • 494
  • 2
  • 5
  • 14
  • 3
    You cannot do that reliably without converting to a string. Numbers are represented as binary floating-point values. – Pointy Jun 01 '19 at 16:31
  • @Pointy: If the number is already in a Number object, there are ways to do it without converting to a string. A Dekker split could be used to separate the value into parts that can be multiplied by 100 without error, and then the integer parts could be separated and manipulated as desired. – Eric Postpischil Jun 01 '19 at 17:32
  • Yes that's possible, but I would consider that tantamount to converting to a string. The OP clearly wants a *number* value that's got the excess fractional bits chopped off, and that's simply not generally possible with binary floating point by its fundamental nature. – Pointy Jun 01 '19 at 17:37
  • 1
    @Pointy: It is possible to compute a Number that is close to the desired decimal value, provided the number is not too large (around 2**53/100), and to use that to produce the desired output or to use it in further calculation with care. – Eric Postpischil Jun 01 '19 at 18:02

1 Answers1

1

You could multiply the value with 100, take the floorished value and divide by 100.

You may witness the wonderful world of floating point arithmetic, where numbers have some more or less decimals, like Is floating point math broken?

function cut(value) {
    return Math.floor(value * 100) / 100;
}

console.log(cut(8.844));
console.log(cut(8.847));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This does not work. For 1.1699999999999999289457264239899814128875732421875, which is representable as a JavaScript Number, multiplying by 100 produces 117, and then `Math.floor(value * 100) / 100` produces the original number, not a result adjusted to 1.16 or near it. – Eric Postpischil Jun 01 '19 at 17:31
  • please have a look to the mentioned link. what you want is impossible with 64 bit float number representation. – Nina Scholz Jun 01 '19 at 17:46
  • No, it is not impossible. I found this number using floating-point arithmetic, and I computed the correct result using fairly ordinary techniques. The number I showed **is** a number that is exactly representable in the Number format, and it **is** a number whose first two decimal digits after the decimal point are 16, and the correct result is computable, and the code you show computes an incorrect result. – Eric Postpischil Jun 01 '19 at 18:00
  • please go ahead. – Nina Scholz Jun 01 '19 at 18:10