امروز به شما دو متد برای تبدیل String به Float در جاوا اسکریپت را آموزش می دهیم.

تبدیل String به Float در جاوا اسکریپت

دو متد برای تبدیل String به Float در جاوا اسکریپت به شرح زیر می باشد :

 

  • Type Conversion

  • ParseFloat

 

 متد اول (Type Conversion) :

مثال :
<script>
 // Javascript script 
// to convert string 
// to float value 
// Function to convert 
// string to float value function convert_to_float(a) { 
// Type conversion 
// of string to float var floatValue = +(a); 
// Return float value return floatValue; 
} 
//Driver code var n = "55.225"; 
// Call function n = convert_to_float(n); 
// Print result document.write("Converted value = " + n + "</br> 
Type of " + n + " = " +typeof n + "<br>"); var n = "-33.565"; 
// Call function n = convert_to_float(n); 
// Print result document.write("Converted value = " + n + "</br>
Type of " + n + " = " +typeof n + "<br>");
</script>

 

نتیجه :

Converted value = 55.225
Type of 55.225 = number
Converted value = -33.565
Type of -33.565 = number

 

متد دوم (ParseFloat) :

مثال :
<script> 
	// Javascript script 
	// to convert string 
	// to float value 
	
	// Function to convert 
	// string to float value 
	function convert_to_float(a) { 
		
		// Using parseFloat() method 
		var floatValue = parseFloat(a); 
		
		// Return float value 
		return floatValue; 
	} 
	
//Driver code 
var n = "245.165"; 
	
// Call function 
n = convert_to_float(n); 
	
// Print result 
document.write("Converted value = " + 
		n + "</br> Type of " + n + " = "
		+typeof n + "<br>"); 

var n = "-915.55"; 
	
// Call function 
n = convert_to_float(n); 
	
// Print result 
document.write("Converted value = " + 
		n + "</br> Type of " + n + " = "
		+typeof n + "<br>"); 
</script> 

 

نتیجه :
Converted value = 245.165
Type of 245.165 = number
Converted value = -915.55
Type of -915.55 = number

 

اگر String شما شامل عدد نباشد یا حرف اول آن عدد نباشد جواب NaN خواهد بود.

از اینکه فرازگر را در این مقاله همرایی کردید از شما سپاسگذاریم.

5/5 - (2 امتیاز)

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *