8
7

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 3 years have passed since last update.

【JavaScript, Java】数値の桁数を取得する方法

Last updated at Posted at 2021-01-24

#プログラミング勉強日記
2021年1月25日
数値の桁数の取得方法に困ったので、備忘録として書く。

#JavaScriptで数値の桁数を取得する

let number = 12345;
let numberDigit = String(number).length;
console.log(numberDigit);   // 5

#Javaで数値の桁数を取得する

int number = 12345;
int numberDigit = String.valueOf(number).length();   
System.out.println(numberDigit);  // 5

#入力した整数値の桁数を出力するプログラム

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>sample</title>

  <script type="text/javascript">
	//数値から桁数を取得する
	function getNumber() {
		// フォームから数値を取得する
		let inputNumber = document.getElementById("number").value; 
		// 取得した数値から整数部分の桁数を取得する
		let integerDigit = parseInt(inputNumber).toString().length; 
		// 桁数を出力する
		let output = "";
		if (inputNumber > 0) {
			output = integerDigit + "";
		}
	document.getElementById("digit").innerHTML = output;
	}
</script>
</head>

<body>
	<form>
		<input type="text" id="number"  onKeyUp="getNumber()">
	</form>
	<p id="digit"></p>
 </body>
</html>

実行結果
image.png

image.png

8
7
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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?