Convert string issue

An input of “5 . 5 . 5” should display 5.55 : expected ‘5.5.5’ to equal ‘5.55’

So I need to convert from 5.5.5 to 5.55 .
How to do that?
Any Help or tips?

How far have you got with this?

Sorry I don’t understand !!!
What do you mean?

What rules is your conversion expected to follow?

for example why is your expected output 5.55 and not 55.5?

IF you know there will always be 2 decimal points you could: remove all ‘.’ and divide by 100.

let num = '5.5.5';
num = num.replace('.','')/100

I suspect that it’s to clean up accidental entries by removing all but the first decimal point.

Assuming that someone entered “5.5.5” into an input field, and we are supposed to remove multiple decimals, that can be done like this:

function dotFilter(str) {
  const firstDotIndex = str.indexOf(".");
  return str.split("").filter(function removeExtraDecimals(char, index) {
    if (char === ".") {
      return index === firstDotIndex;
    }
    return true;
  }).join("");
}

Which in the context of a form with other possible sanitise methods, could be included with the following:

function sanitise(field) {
  if (field.name === "price") {
    return dotFilter(field.value);
  }
}

function fieldChangeHandler(evt) {
  const field = evt.target;
  field.value = sanitise(field);

}
const formFields = document.querySelectorAll("input");
formFields.forEach(function addEventHandler(field) {
  field.addEventListener("change", fieldChangeHandler);
});

Here’s an example page to play with: https://jsfiddle.net/841mfg23/

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.