I need to verify and manipulate a numeric string. In this example, I have this string "1.59945,5|10". The "," and "|" are delimiters, so it has three separate values: 1.59945, 5 and 10. I want to round off any float values (In this case 1.59945) to the nearest 2 decimal places before saving the entire string back to the database. The result should be "1.60,5|10".
Here's the JsFiddle
let values = "1.59945,5|10"
const separators = values.split("").filter(v=>{
return v === "," || v=== "|"
})
const regex = new RegExp(`,|\\|`);
values = values.split(regex).map(value=>{
if (value.includes(".")) {
return parseFloat(value).toFixed(2)
} else {
return value;
}
}).join(",")
separators.forEach(separator=>{
values = values.replace(",",separator)
})
console.log(values)
The code seems to achieve what I want, but is there a more concise / better way of doing it?
I think, we can do like this;
var string = "1.59945,5|10";
string.match(/\d+\.?\d*/).forEach((s) => { //Adjust your regex accordingly
//you can add validation here also
string = string.replace(s, parseFloat(s).toFixed(2));
});
console.log(string);
Simple regular expression with replace can get rid of all the looping
// If only the first is a float
const values = "1.59945,5|10"
console.log(values.replace(/^([\d.]+)/, function(n) {
return Number(n).toFixed(2);
}));
// If any of them can be floats
const values2 = "1.59945,5.446|10";
console.log(values2.replace(/([\d.]+)/g, function(n) {
return n.includes(".") ? Number(n).toFixed(2) : n;
}));