Home Web Front-end JS Tutorial How to convert Number and String to each other in javascript

How to convert Number and String to each other in javascript

Apr 09, 2018 am 10:18 AM
javascript string Convert


The content of this article is to share with you how to realize the mutual conversion of Number and String in JavaScript. It has certain reference value. Friends in need can refer to it

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number和String之间的互相转换</title>
<script type="text/javascript">
//将Number数字转换成String字符串
//第一种方法是使用String()函数,该方法有局限性,即无法将某个数值转换成不同进制的,也无法选取有效数字等等
var num = 123456.7897;
var str = String(num);
console.log("String(" + num + ") = " + str);
//第二种方法是使用Number对象的toString()方法,toFixed()方法,toExponential()方法,toPrecision()方法
//toString()方法默认将Number转换成十进制数
str = num.toString();
console.log(num + ".toString() = " + str);
//toString(radix)方法可以带一个参数radix,表示将Number按照提供的进制转换,进制范围2-36,如果超出这个范围将报错。
str = num.toString(2);
console.log(num + ".toString(2) = " + str);
//toFixed()方法,如果不提供参数的话默认是精确到个位,四舍五入法,不使用指数计数法
str = num.toFixed();
console.log(num + ".toFixed() = " + str);
//toFixed(float)方法可以带一个参数,表示精确到小数点后面第几位,如果参数为0,和不提供参数功能相同
str = num.toFixed(1);
console.log(num + ".toFixed(1) = " + str);
//toExponential方法,该方法使用指数计数法转换数值,小数点前只有一位,小数点后面的位数由参数指定,默认情况下不会截取位数
str = num.toExponential();
console.log(num + ".toExponential() = " + str);
//toExponential方法带参数代表小数点后保留的位数
str = num.toExponential(1);
console.log(num + ".toExponential(1) = " + str);
//toPrecision()方法按照参数指定的有效数字个数转换数值,默认不给参数的情况下保留所有有效数字位
str = num.toPrecision();
console.log(num + ".toPrecision() = " + str);
//toPrecision()可以带一个参数,代表有效数字位数,如果该位数小于原数的整数部分位数,则用指数形式表示,否则用非指数形式。
str = num.toPrecision(6);
console.log(num + ".toPrecision(6) = " + str);
//将String字符串转换成Number也有两种方式
//第一种方式仍然使用显示转换函数Number,可以转换整数和浮点数,但是这种方法不允许待转换的字符串中出现任何非法字符,包括空格,如果存在非法字符,将得到结果NaN。
str = "12 3";
num = Number(str);
console.log("Number(" + str + ") = " + num);
//第二中方式是使用全局函数parseInt()和parseFloat()
//parseInt()方法只能解析整数,会忽略所有的前导空白字符,直到解析到某个非法非空白字符为止,小数点在parseInt()被认为是非法字符,如果中间出现空格,也会被认为是非法字符。
str = "a .1 1.8";
num = parseInt(str);
console.log("parseInt(" + str + ") = " + num);
//parseInt()方法的第二个参数是进制,默认情况下回以十进制去解析。
str = "0xff";
num = parseInt(str, 16);
console.log("parseInt(" + str + ",16" + ") = " + num);
//parseFloat()方法可以解析整数和浮点数,它会将小数点解析成合法字符,如果第一个字符就是小数点,则会被解析成0.xxx,但是parseFloat()方法不能更换进制 ,得明确告诉它是多少进制,比如十六进制加0x,实践证明,明确告诉也没用
//0xff会被解析成0...,parseInt()方法带不带第二个参数都能解析成255
str = "0xff";
num = parseFloat(str);
console.log("parseFloat(" + str + ") = " + num);
</script>
</head>
<body>
</body>
</html>
Copy after login

Related recommendations:

JS Number String Conversion

Shortcut method for string and number type conversion

##Convert string string type to number numeric type

The above is the detailed content of How to convert Number and String to each other in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

How to convert AI files to CDR format How to convert AI files to CDR format Feb 19, 2024 pm 04:09 PM

AI files refer to vector graphics files created by Adobe Illustrator (AI for short) software, while CDR files refer to vector graphics files created by CorelDRAW software. Since these two softwares are developed by different manufacturers, their file formats are different and cannot be directly converted to each other. However, we can convert AI files to CDR files through some methods. A commonly used conversion method will be introduced below. Step 1: Export AI files to EPS format AdobeIllust

How to convert ODT to Word in Windows 11/10? How to convert ODT to Word in Windows 11/10? Feb 20, 2024 pm 12:21 PM

In this article, we will show you how to convert OpenDocumentTextDocument (ODT) files to Microsoft Word (Docx, DOC, etc.). Format. How to Convert ODT to Word in Windows 11/10 Here is how you can convert ODT documents to DOC or DOCX format on Windows PC: Convert ODT to Word using WordPad or Word The first method we are going to show you Is to use WordPad or MicrosoftWord to convert ODT to Word. Here are the steps to achieve this: First, open the WordPad app using the Start menu. Now, go to

How to convert a virtual machine to a physical machine? How to convert a virtual machine to a physical machine? Feb 19, 2024 am 11:40 AM

Converting a virtual machine (VM) to a physical machine is the process of migrating a virtual instance and associated application software to a physical hardware platform. This conversion helps optimize operating system performance and hardware resource utilization. This article aims to provide an in-depth look at how to make this conversion. How to implement migration from virtual machine to physical machine? Typically, the conversion process between a virtual machine and a physical machine is performed outside the virtual machine by third-party software. This process consists of multiple stages involving the configuration of virtual machines and the transfer of resources. Prepare the physical machine: The first step is to ensure that the physical machine meets the hardware requirements for Windows. We need to back up the data on a physical machine as the conversion process will overwrite the existing data. *Username and password for an administrator account with administrator rights to create system images. will be virtual

Golang time processing: How to convert timestamp to string in Golang Golang time processing: How to convert timestamp to string in Golang Feb 24, 2024 pm 10:42 PM

Golang time conversion: How to convert timestamp to string In Golang, time operation is one of the very common operations. Sometimes we need to convert the timestamp into a string for easy display or storage. This article will introduce how to use Golang to convert timestamps to strings and provide specific code examples. 1. Conversion of timestamps and strings In Golang, timestamps are usually expressed in the form of integer numbers, which represent the number of seconds from January 1, 1970 to the current time. The string is

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

Java Apache Camel: Building a flexible and efficient service-oriented architecture Java Apache Camel: Building a flexible and efficient service-oriented architecture Feb 19, 2024 pm 04:12 PM

Apache Camel is an Enterprise Service Bus (ESB)-based integration framework that can easily integrate disparate applications, services, and data sources to automate complex business processes. ApacheCamel uses route-based configuration to easily define and manage integration processes. Key features of ApacheCamel include: Flexibility: ApacheCamel can be easily integrated with a variety of applications, services, and data sources. It supports multiple protocols, including HTTP, JMS, SOAP, FTP, etc. Efficiency: ApacheCamel is very efficient, it can handle a large number of messages. It uses an asynchronous messaging mechanism, which improves performance. Expandable

See all articles