LoginSignup
1
0

正規表現によって小数末尾のゼロを削除する

Posted at

以下の正規表現で数値文字列を置換すれば、小数末尾のゼロを削除できる。

target.replace(/((?<=\.\d+)|\.)0+$/, '');

JavaScriptでの実際の動作は以下の通り。

index.js
const trimDecimalZero = (target) => target.replace(/((?<=\.\d+)|\.)0+$/, '');

console.log(trimDecimalZero('1.200')); // 1.2
console.log(trimDecimalZero('10.00')); // 10
console.log(trimDecimalZero('12300')); // 12300
console.log(trimDecimalZero('1.234')); // 1.234

ただし、正規表現の実装によっては肯定戻り読みの量指定子に未対応なので、上記のとおりに動作しない言語やライブラリもある。

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