Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to remove non-digits and keep up to one decimal place in JS

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to remove non-digits and retain at most one decimal place in JS. The article is very detailed and has certain reference value. Friends who are interested must read it!

The implementation code in js that removes non-numeric places and retains at most one decimal place is as follows:

/ / remove non-numeric var clearNoNum = function (item) {if (itemized null & & itemized undefined) {/ / replace all non-numeric items first, except for numbers and. Item = item.replace (/ [^\ d.] / g, "); / / must ensure that the first one is a number instead of. Item = item.replace (/ ^\. / g, ""); / / guarantee that only one appears. But not more than one. Item = item.replace (/\. {2,} / g, ""); / / guarantee. Item = item.replace (".", "$# $"). Replace (/\. / g, "). Replace (" $# $",". "); / / keep at most one decimal place var arr = item.split (". "); if (arr.length > 1) item = arr [0] +'.'+ (arr [1] .length > 1? Arr [1] .substr (0,1): arr [1]);} return item;}

Add:

Let's take a look at the number processed by js to retain 2 decimal places, which is not enough to make up for. 00.

1. Retain two decimal places / / function: round the floating point to 2 decimal places

2. / the system retains 2 decimal places, such as 2, which will be followed by 00. That is, 2.00

Test / / retains two decimal places / / function: round the floating point to function toDecimal (x) {var f = parseFloat (x) after the decimal point; if (isNaN (f)) {return;} f = Math.round (xx 100) / 100; return f;} / / keep 2 decimal places, such as 2, adding 00 after 2. That is, 2.00 function toDecimal2 (x) {var f = parseFloat (x); if (isNaN (f)) {return false;} var f = Math.round (xx 100) / 100; var s = f.toString (); var rs = s.indexOf ('.'); if (rs < 0) {rs = s. } while (s.length

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report