0

I'd like to calculate 1538422.986611792949856002 - 1

Expecting value is 1538421.986611792949856002 (showing 18 decimals is the point.)

I think I need to make those two numbers to string since functions such as parseFloat, Number don't show the 18 decimals and subtract those two strings??

shortcut Calculate string values but keep 18 decimals.

Mijeong Won
  • 291
  • 5
  • 16

2 Answers2

1
eval("1538422.986611792949856002 - 1").toFixed(18)
Rahul Kumar
  • 5,120
  • 5
  • 33
  • 44
Biplab Malakar
  • 750
  • 6
  • 11
  • I tried that in console.log and the output is 1538421.986611793050542474. not 1538421.986611792949856002. Why is that? – Mijeong Won Oct 31 '18 at 04:58
  • because of floating-point problem in computer. https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems https://stackoverflow.com/questions/963873/1-265-10000-126499-99999999999 – Biplab Malakar Oct 31 '18 at 05:02
  • Damn, There's no way to calculate to see the output 1538421.986611792949856002 then?? I don't want to use a library – Mijeong Won Oct 31 '18 at 05:13
  • No, you can't get the exact output you want but you can get approx output using Math.fround(eval("1538422.986611792949856002 - 1")).toFixed(18) – Biplab Malakar Oct 31 '18 at 05:17
  • You can solve this problem by deviding the number in two part foloating part and not floating part. And perform opration between floating part of num1, num2 and non-floating part of num1, num2. Then concate the result. – Biplab Malakar Oct 31 '18 at 05:27
  • You should show how to actually solve AND perhaps add all those comments to the answer. As it stands without the comments it does not provide an accurate answer. – Mark Schultheiss Oct 31 '18 at 11:04
0

I got a help from Locutus which seeks to assimilate other languages’ standard libraries to JavaScript.

I used bcsub to calculate 1538422.986611792949856002 - 1. The feature which is from php makes number to string so that we can avoid the floating-point problem in computer.

You can find more informations here.

Mijeong Won
  • 291
  • 5
  • 16