4

I am trying to solve a particular JavaScript exercise involving recurring numbers and in doing so I need to work with recurring numbers to a good amount of decimal places.

Currently I am using:

function divide(numerator, denominator){
    var num = (numerator/parseFloat(denominator);
}
// 7/11 = 0.6363636363636364
// 5/3 = 1.6666666666666667
// 3/8 = 0.375

As you can see, the results of the operation that contain recurring digits are returned with the final digit rounded. It is tempting to simply convert to array and pop() the last digit of each number but this leads to problems when we run into numbers that are not recurring such as 3/8 =0.375.

How can I divide two numbers and get a result that such as 5/3 = 1.666666666666666 ? (essentially the last digit is rounded down and never rounded up)

Thanks for your help.

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Didgeridude
  • 123
  • 6
  • 1
    Have you looked at any of the Big-Number options? There is a new option in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt but also a few 'external' libraries – MikeB Dec 20 '19 at 11:50
  • I have taken a look at BigInt as an option but couldn't see a solution that would enable me to handle decimals. It's possible there is a way using BigInt but if there is, I do not currently know the methodology. – Didgeridude Dec 20 '19 at 14:52
  • Sorry, I forgot that was integer-only, but if you search for "alternatives to js bigint" then you should find plenty of libraries, the first I found was https://bellard.org/quickjs/jsbignum.html which certainly has bigFloat functionality. – MikeB Dec 20 '19 at 16:41
  • See this https://floating-point-gui.de/languages/javascript/ – aksappy Dec 20 '19 at 16:45
  • Related: [Algorithm for detecting repeating decimals?](https://stackoverflow.com/q/1315595/215552) – Heretic Monkey Dec 20 '19 at 17:28

1 Answers1

0

For simple cases, I typically use the round-to npm package:

import roundTo from 'round-to';

const num = 5/3; // 1.6666666666666667
// set your desired number of decimal places:
const numDecimalPlaces = (num + "").split(".")[1].length; 
// Based on your question, I think this is what you are trying to achieve:
const roundedDown = roundTo.down(num, numDecimalPlaces - 1); // 1.6666666666666667
// You can also do these:
const rounded = roundTo(num, numDecimalPlaces); // 1.6666666666666667
const roundedUp = roundTo.up(num, numDecimalPlaces); // 1.6666666666666667

If you don't want to install their package, you can copy their implementation from Github. Their source code is pretty easy to follow.

bfla
  • 71
  • 2