0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

React input時に、小数点を数字で表示する方法

Posted at

例えば、数値が「0.00000001」のように小数点以下8桁必要な場合、入力値のフォーマットを8桁固定にする必要があります。以下に2つのアプローチを示します。

1. 制御コンポーネントとして onBlur でフォーマットする方法

入力値を state で管理し、フォーカスアウト時に toFixed(8) を使って小数点以下8桁にフォーマットします。

import * as React from 'react';
import { Input } from '@/components/ui/input';

export const EightDecimalInput = () => {
  const [value, setValue] = React.useState<string>('0.00000001');

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // 数字と小数点のみを許容する簡易チェック
    if (/^[0-9]*\.?[0-9]*$/.test(e.target.value)) {
      setValue(e.target.value);
    }
  };

  const handleBlur = () => {
    const num = parseFloat(value);
    if (!isNaN(num)) {
      // 小数点以下8桁に固定
      setValue(num.toFixed(8));
    }
  };

  return (
    <Input
      type="text"
      value={value}
      onChange={handleChange}
      onBlur={handleBlur}
      placeholder="0.00000001"
    />
  );
};

この方法では、ユーザーが入力後に必ず小数点以下8桁で表示されるようになります。

2. react-number-format を利用する方法

外部ライブラリ react-number-format を使うと、入力中も常にフォーマットを維持できます。以下は Shadcn の Input コンポーネントと組み合わせる例です。

まず、ライブラリをインストールします。

npm install react-number-format

次に、以下のように実装します。

import * as React from 'react';
import NumberFormat from 'react-number-format';
import { Input } from '@/components/ui/input';

export const EightDecimalNumberFormatInput = () => {
  return (
    <NumberFormat
      customInput={Input}              // Shadcn の Input を利用
      decimalScale={8}                 // 小数点以下8桁に固定
      fixedDecimalScale={true}         // 8桁を常に表示
      allowNegative={false}            // 必要に応じてマイナス値の入力を禁止
      value="0.00000001"
      placeholder="0.00000001"
    />
  );
};

この方法では、入力中も「0.00000001」のように8桁固定で表示され、ユーザー体験が向上します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?