Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda