0

i have strings that represents money. E.g 29.00 or 29.10 or 29.13 the currency however can change and does not necessarily lead to a value that has two decimal places by default (Yen for example does not have decimal places at all)

Now, i use Decimal.js to execute calculations with these values

For example i am multiplying with a percentage

let d = new decimal("29.00")
let e = d.mul(0.133333333333).toDP(d.decimalPlaces())

The result of this however is rounded to 0 decimal places as the constructer strips away the trailing zeros and sets decimalPlaces to 0.

How can i get a decimal value that always has to amount of decimal places provided by the input string? In this example d.decimalPlaces should return 2 (because 29.00 has to decimal places).

Alternative solution: How do i extract the number of decimal places out of the string?

4

1 回答 1

2

You mean this?

const keepDecimal = (str,mul) => {
  const dec = str.split(".");
  const numDec = dec.length===2?dec[1].length:0;
  return (str*mul).toFixed(numDec);
}

console.log(keepDecimal("29.13",0.133333333333))
console.log(keepDecimal("29",0.133333333333))

于 2020-08-13T17:43:12.590 回答