I am new to JavaScript and I wanted to truncate numbers (23.123) to 23.
arr = [
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123]
]
I tried Math.trunc and even with lodash (_.toInteger) but was not getting results. I may have screwed in logic.
I need output like this.
output = [
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
]
I just wanna know how can we achieve this.
CodePudding user response:
you can use toFixed()
const arr = [
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123]
]
const nestedArr = arr.map(nestedArr => nestedArr.map(item => item.toFixed(0)))
console.log(nestedArr)
CodePudding user response:
Maybe this will help you.
const arr = [
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123]
]
const allEls = arr.map((el) => {
return el.map((num) => Math.trunc(num))
})
console.log(allEls)
CodePudding user response:
I believe you should use Math.trunc function
let arr = [
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123]
];
for(let i=0;i<arr.length;i ){
for(let j=0;j<arr[i].length;j ){
arr[i][j] = Math.trunc(arr[i][j]);
}
}
console.log(arr);
CodePudding user response:
Have you tried the method parseInt ?
var arr = [
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123],
[1.05, 2.0123, 3.123, 4.123]
];
for(var i = 0; i < arr.length; i )
{
var newArray = arr[i];
for(var bis = 0; bis < newArray.length; bis )
{
console.log(parseInt(newArray[bis]));
}
}
See the doc : https://www.w3schools.com/jsref/jsref_parseint.asp
Hope this helps you.