Get the App
SLTechnology News&Howtos  ›  Development  › 

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

Shulou Source: shulou.com Published: 2022-06-03 20:02:39 10月01日 Update

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

Tags: Decimal number decimal point precision science technology science and technology rounding rounding guarantee mandatory content function points articles not enough code value interest only Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Docker MySQL Shulou Information Apple