Home > Blockchain >  other language digit conversion to english issue in React
other language digit conversion to english issue in React

Time:01-29

i have a simple react application containing a input field i want when the user types string it should not accept and convert arabic digits to english also accept upto 2 decimal digits .curently its doing the conversion but not accepting decimal points

import React, { useState } from "react";
export default function App() {
  const [val, setVal] = useState(0);
  function ARtoENPrice(input) {
    console.log({ stype: typeof input, input });
    if (typeof input === "string") {
      input = input?.trim();
      const arabicNums = ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"];
      let output = "";
      let decimal = false;
      for (let i = 0; i < input.length; i  ) {
        if (arabicNums.indexOf(input[i]) !== -1) {
          output  = arabicNums.indexOf(input[i]);
        } else if (input[i] === "." || !isNaN(input[i])) {
          if (input[i] === ".") {
            if (decimal === true) continue;
            decimal = true;
          }
          output  = input[i];
        }
      }
      if (output === "") return "";
      if (output === ".") return output;
      return parseFloat(output);
    } else {
      if (input === null || input === undefined || input == NaN) return "";
      return Number(input)?.toFixed(2);
    }
  }

  const handleChange = (e) => {
    let v = ARtoENPrice(e.target.value);
    setVal(v);
  };
  return (
   
      <input type="text" value={val} onChange={handleChange} />
     
  );
}

CodePudding user response:

Here's a modification to the ARtoENPrice function that only allows two decimal points:

function ARtoENPrice(input) {
  if (typeof input === "string") {
    input = input.trim();
    const arabicNums = ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"];
    let output = "";
    let decimalCount = 0;
    for (let i = 0; i < input.length; i  ) {
      if (arabicNums.indexOf(input[i]) !== -1) {
        output  = arabicNums.indexOf(input[i]);
      } else if (input[i] === "." || !isNaN(input[i])) {
        if (input[i] === ".") {
          decimalCount  ;
          if (decimalCount > 2) continue;
        }
        output  = input[i];
      }
    }
    return output;
  } else {
    return Number(input).toFixed(2);
  }
}
  • Related