Formatting very large numbers to local settings in javascript

41 Views Asked by At

I saw the question here How can I format big numbers with toLocaleString? but this doesn't exactly answer the questino I have.

I'm using the library provided by https://github.com/royNiladri/js-big-decimal which allows for very large number calculations (not just integers). The main issue I have is that there is no way to use ".toLocaleString()". There are "ways" around this (for example, using numeral), but in all the solutions I can find, you have to specify the locales yourself.

Is there any library that will automatically take a string (which is a number) and format it to fit the automatically generated locale of the user?

Example:

import bigDecimal from "js-big-decimal";

var x = new bigDecimal('1.0e148')
var y = x.divide(new bigDecimal('3'))
console.log(y.toLocaleString())

should print out the appropriate string.

1

There are 1 best solutions below

5
hasan darwish On

So, simply, to achieve this, you need to get the number first as a string :

const n = new bigDecimal('1.0e148')
const number = n.divide(new BigDecimal('3')
const string = number.toString() // You can look for it in the documentation, toString() is available

Now, we need to get the part of string that is after the point :

const afterPointString = string.slice(string.indexOf("."))

and now, we need to define how many digits you need after the point :

const numbersAfterDecimal = 5 // For example, put any number
const resultNumberAfterDecimal = Math.floor(Int(afterPointString)/Math.pow(10, numbersAfterDecimal))*Math.pow(10, numbersAfterDecimal)

const result = new BigDecimal(string.slice(0, string.indexOf(".")+1) + String(resultNumberAfterDecimal))

this code is not tested, so please test it and tell me what happens with you