JavaScript retrieves the decimal places of any float type

Source: Internet
Author: User

Use Javascript to get the first two digits of the float decimal point. For example, 22.127456 is used to get 22.13. How can this problem be solved?

1. This method is not recommended at all:

Function get () {var s = 22.127456 + ""; var str = s. substring (0, s. indexOf (".") + 3); alert (str );}

2. Use a regular expression to obtain:

Function get () {var a = "23.456322"; var aNew; var re =/([0-9] + \. [0-9] {2}) [0-9] */; aNew =. replace (re, "$1"); alert (aNew );}


3. relatively advanced applications:

Function get () {var num = 22.127456; alert (Math. round (num * 100)/100 );}

4. The simplest and most convenient:

Function get () {var num = new Number (13.37); num = num. toFixed (2); // 2 is the number of digits after the decimal point is obtained. It is automatically rounded to alert (num );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.