Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
Looking for a better way of manipulating a numeric string that contains delimiters

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

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;
}));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!