-1

So let's say I have a string like this:

'6,18284828814828481'

Javascript Number do support a certain amount of decimals. from what I see I should return something like this:

6.182848288148285

Is there a way I can convert the string to the closest valid number?

What I try to do is something like this:

  const limitDecimals = (num: string): string|number => {
let maxDecimalDigits = 17;
for(let i = maxDecimalDigits; i >= 0; i--) {
  let [integerPart, decimalPart] = num.split('.');
  if(decimalPart){
    decimalPart = decimalPart.slice(0, i);
    if(decimalPart.length > 0) {
      return`${integerPart}.${decimalPart}`;
    }
  }else{
    return integerPart;
  }
}
return num;
}

Note: this is not converted in Number since it would not work yet

jabaa
  • 5,844
  • 3
  • 9
  • 30
  • 2
    Do you mean `parseFloat('6,18284828814828481'.replace(',', '.'))`? _"Javascript Number do support a certain amount of decimals."_ That's not correct. It's more complex. – jabaa Jan 13 '23 at 14:21
  • I don't understand what you are asking. You ask about getting the closest valid **number**, but your function returns a **string**. Can you clarify and provide some examples of input and expected output? – trincot Jan 13 '23 at 14:43

2 Answers2

0

parseFloat(string) should work for what you want?

You would replace ',' (comma) to '.' at string '6,18284828814828481' and pass to parseFloat:

var result = window.parseFloat('6,18284828814828481'.replace(",", "."));
//expected result: 6.182848288148285 
1chard
  • 1
  • 1
0

unfortunately by default js is not enough precise to let you manipulate number with a big amount of decimal.

a way to do it is to use an external library for sample like decimal.js

const data = '6,18284828814828481';
const limitDecimals = function(num, precision) {
  num = new Decimal(num.replace(',', '.'));
  return num.toPrecision(precision);
}

console.log(limitDecimals(data, 17));
console.log(limitDecimals(data, 16));
console.log(limitDecimals(data, 15));
console.log(limitDecimals(data, 14));
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js" integrity="sha512-zPQm8HS4Phjo9pUbbk+HPH3rSWu5H03NFvBpPf6D9EU2xasj0ZxhYAc/lvv/HVDWMSE1Autj19i6nZOfiVQbFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
jeremy-denis
  • 6,368
  • 3
  • 18
  • 35