如何在Javascript中将小数点上移一个位置?

How to move decimal up a position in Javascript?

提问人:Adnan Ashraf 提问时间:8/30/2023 最后编辑:Adnan Ashraf 更新时间:9/5/2023 访问量:107

问:

所以基本上,我们拥有初始值0.00

如果用户输入任何值(如 2),则十进制值应为 0.02

如果用户输入任何值(如 3),则十进制值应为 0.23(附加到前一个值 0.02)

如果用户输入任何值(如 5),则十进制值应为 2.35(附加到前一个值 0.23)

因此,如果用户输入了 12345,则应该是 123.45 。

我想要这样的东西

enter image description here

javascript reactjs 数字格式化 react-native-textinput

评论


答:

2赞 Maze 8/30/2023 #1

你似乎要求将一个数字除以十,但我可能不明白这个问题。代码如下:

function d() {n=prompt("enter your number"); alert(n/100);}
button {
position: absolute;
top: 50%;
left: 50%;
}
<button onclick = "d();">move decimal</button>

0赞 Zenb0t 8/30/2023 #2

您应该将输入视为字符串,将数字推到末尾,然后转换回数字。

 let strValue = currentValue.toFixed(2).replace(".", ""); // Remove the decimal
 strValue = (parseInt(strValue, 10) * 10 + digit).toString(); // Shift left and add the new digit
 return parseInt(strValue, 10) / 100; // Convert back to a number with two decimal places
};

举个例子:

let currentValue = 0.00;
currentValue = addDigitToRight(currentValue, 2); // 0.02
currentValue = addDigitToRight(currentValue, 3); // 0.23
currentValue = addDigitToRight(currentValue, 4); // 2.34

0赞 Jerry 8/30/2023 #3

在这里,它设法与如果 last digits are 00;

function decimalUtil(num){
  return (num/100).toFixed(2);
}

console.log(decimalUtil(1200)); //12.00
console.log(decimalUtil(1222)); //12.22
console.log(decimalUtil(12)); //0.12
console.log(decimalUtil(12225588)); //122255.88

0赞 Nawaaz Kortiwala 8/30/2023 #4

下面是 TypeScript 中的 ReactJS 实现:

import { ChangeEvent, FC, useState } from "react"

const DecimalizedInput: FC = () => {
  const [value, setValue] = useState(0)

  /**
   * Decimalizes the value
   * @param {string} targetValue
   * @returns {number}
   */
  const decimalize = (targetValue: string) => {
    const currentValue = parseFloat(targetValue)

    /**
     * For handling value deletion
     */
    if (currentValue < value) return currentValue / 10
    /**
     * For handling value addition
     */
    return currentValue * 10
  }

  const onValueChange = (e: ChangeEvent<HTMLInputElement>) => {
    const targetValue = e.target.value
    /**
     * Ignoring non-numeric characters
     */
    if (targetValue && !targetValue.match(/^\d+(\.\d+)?$/)) return
    /**
     * Decimalizing the value
     */ else if (targetValue) setValue(decimalize(targetValue))
    /**
     * Resetting the value
     */ else setValue(0)
  }

  return (
    <div>
      <input
        value={
          // For displaying the value with 2 decimal places
          value.toFixed(2)
        }
        onChange={onValueChange}
      />
    </div>
  )
}

export default DecimalizedInput

您也可以在此处获取代码。

评论

0赞 Nawaaz Kortiwala 8/30/2023
@AdnanAshraf这也适用于值删除。