1
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?

More than 5 years have passed since last update.

【TypeScript】文字型の数値を文字型のまま減算する処理

1
Last updated at Posted at 2020-01-09

"12345678901234567890"のように桁数が多い数値の場合、

Number("12345678901234567890") === 12345678901234567000 // true

となってしまいます。

自分の作っているアプリでこのような桁の大きい文字型の数値から1だけマイナスしたかったので下記のような関数を作りました。

export const decrease = (snowflake: string): string | null => {
  if (!/^([1-9]\d*|0)$/.test(snowflake)) return null;

  let i = 1;
  while (snowflake[snowflake.length - i] === "0") { i++; }

  const tail = snowflake.slice(-i);
  let tailDec = String(Number(tail) - 1);
  if (tailDec.length < tail.length) tailDec = "0" + tailDec;

  return snowflake.slice(0, -i) + tailDec;
}
実行
console.log(decrease("12345678901234567890"));
// 12345678901234567889
1
0
2

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
1
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?