I`m looking for a way to delete the last Digits from an Input with comma if the Value is more then 4.
Example:
Value : 13,314556 should be -> 13,3145.
Is there a way to just remove everything then the last 4 digits of this number with something like this?
let value = 13,314556
let result= value.split(',')[1].trim();
if(result.length > 4){
...
}
You can call toFixed() to format the number to a number of decimal places.
See MDN Documentation for toFixed()
Modified from the example given in the above documentation:
function myFormat(x) {
return Number.parseFloat(x).toFixed(4);
}
// expected output: "13.3146" because of rounding
console.log(myFormat(13.314556));
// expected output: "0.0040"
console.log(myFormat(0.004));
// expected output: "123000.0000"
console.log(myFormat('1.23e+5'));
If you don't want rounding, simply be more precise and clip the end of the resulting string.
function myFormat(x) {
return Number.parseFloat(x).toFixed(6).replace(/\d\d$/, '');
}
// expected output: "13.3145", will not do rounding
console.log(myFormat(13.314556));
If you are working with currency or do similar important calculations, consider working with a library like decimal.js.
alternative is to multiply by 10000, floor it, then divide by 10000.
let value = 13.314556;
value=Math.floor(value*10000)/10000;
console.log(value)
or if you want to control the number of digits programmatically you could use something like this:
let value = 13.314556;
value=Math.floor(value*Math.pow(10, 4))/Math.pow(10, 4);
console.log(value)
I would do it with the slice and join methods
Slice for slicing the string with the length you want
Join to re-create the number as you wish
I added check if comma is in the number and also a parameter with the desired length
function splitNumber(num, nbAfterComa) {
const number = num.toString()
if(!number.includes('.')){
return number
}
const splitedValue = number.split('.')
splitedValue[1] = splitedValue[1].trim().slice(0, nbAfterComa);
return nbAfterComa > 0 ? splitedValue.join(',') : splitedValue[0]
}
console.log(splitNumber(13.314556, 4))
console.log(splitNumber(13.3, 4))
console.log(splitNumber(13.314556, 1))
console.log(splitNumber(13.314556, 0))
console.log(splitNumber(13, 8))