Home Web Front-end JS Tutorial JS formats numerical amounts separated by commas and retains two decimal places_javascript skills

JS formats numerical amounts separated by commas and retains two decimal places_javascript skills

May 16, 2016 pm 05:19 PM
js format

For example:
12345 is formatted as 12,345.00
12345.6 is formatted as 12,345.60
12345.67 is formatted as 12,345.67
Leave only two decimal places.
After I came back, I wrote a formatting function. You can control the number of decimal places and automatically round off. The code is as follows:

Copy code The code is as follows:

function fmoney(s, n) {
n = n > 0 && n <= 20 ? n : 2;
s = parseFloat((s "").replace(/[^d.-]/g, "")).toFixed (n) "";
var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
t = "";
for (i = 0; i < l.length; i ) {
t = l[i] ((i 1) % 3 == 0 && (i 1) ! = l.length ? "," : "");
}
return t.split("").reverse().join("") "." r;
}

Call: fmoney("12345.675910", 3), return 12,345.676
Restore function:
Copy code The code is as follows:

function rmoney(s) {
return parseFloat(s.replace(/[^d.-]/g, ""));
}

Example (you can save the code as an html file and run it to see the effect):
Copy the code The code is as follows :

<SCRIPT> <br>function fmoney(s, n) { <br>n = n > 0 && n <= 20 ? n : 2; <BR>s = parseFloat((s "").replace(/[^d.-]/g, "")).toFixed(n) ""; <BR>var l = s.split(".")[0]. split("").reverse(), r = s.split(".")[1]; <BR>t = ""; <BR>for (i = 0; i < l.length; i ) { <BR>t = l[i] ((i 1) % 3 == 0 && (i 1) != l.length ? "," : ""); <BR>} <BR>return t.split ("").reverse().join("") "." r; <BR>} <BR>function rmoney(s) { <BR>return parseFloat(s.replace(/[^d.-]/ g, "")); <BR>} <BR>function g(id) { <BR>return document.getElementById(id); <BR>} <BR>window.onload = function() { <BR>var num, txt = g("txt"), txt2 = g("txt2"), btn = g("btn"), btn2 = g("btn2"), span = g("span"); <BR> btn.onclick = function() { <BR>num = parseInt(g("num").value); <BR>txt.value = fmoney(txt.value, num); <BR>txt2.value = fmoney( txt2.value, num); <BR>}; <BR>btn2.onclick = function() { <BR>num = parseInt(g("num").value); <BR>span.innerHTML = "=" <BR> fmoney(rmoney(txt.value) rmoney(txt2.value), num); <BR>}; <BR>}; <BR></SCRIPT>
Decimal points:
< ;select id="num">


< option value="4">4









Attach:
Copy code The code is as follows:

/*
* formatMoney(s,type)
* Function: Split the amount by commas in thousands
* Parameter: s, the amount value that needs to be formatted.
* Parameter : type, determine whether the formatted amount requires decimal places.
* Return: Return the formatted numerical string.
*/
function formatMoney(s, type) {
if ( /[^0-9.]/.test(s))
return "0";
if (s == null || s == "")
return "0";
s = s.toString().replace(/^(d*)$/, "$1.");
s = (s "00").replace(/(d*.dd)d*/ , "$1");
s = s.replace(".", ",");
var re = /(d)(d{3},)/;
while (re. test(s))
s = s.replace(re, "$1,$2");
s = s.replace(/,(dd)$/, ".$1");
if (type == 0) {// Without decimal places (default is with decimal places)
var a = s.split(".");
if (a[1] == "00") {
s = a[0];
}
}
return s;
}
/*
* General DateAdd(interval,number,date) Function: Implementation Date addition function of javascript.
* Parameter: interval, string expression, indicating the time interval to be added. Parameter: number, numerical expression, indicating the number of time intervals to be added. Parameter: date, time Object.
* Return: new time object. var now = new Date(); var newDate = DateAdd("day",5,now);
* author:devinhua(starting from ○) update:2010 -5-5 20:35
*/
function DateAdd(interval, number, date) {
if (date == null)
return "";
switch (interval) {
case "day":
date = new Date(date);
date = date.valueOf();
date = number * 24 * 60 * 60 * 1000;
date = new Date(date);
return date;
break;
default:
return "";
break;
}
}
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)

How to format c drive with dos command How to format c drive with dos command Feb 19, 2024 pm 04:23 PM

DOS command is a command line tool used in Windows operating system, which can be used to perform various system management tasks and operations. One of the common tasks is to format the hard drive, including the C drive. Formatting the C drive is a relatively dangerous operation because it will erase all data on the C drive and reinitialize the file system. Before performing this operation, make sure you have backed up important files and have a clear understanding of the impact that formatting will have on your computer. The following is formatted in the DOS command line

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) May 04, 2024 pm 06:01 PM

Nowadays, we will inevitably encounter some problems such as being unable to turn on the phone or lagging, such as system crash, but during use, mobile phones have become an indispensable part of our lives. We are often at a loss, and sometimes, there are no solutions to these problems. To help you solve cell phone problems, this article will introduce you to some methods of cell phone format recovery and restore your phone to normal operation. Back up data - protect important information, such as photos and contacts, from being lost during the formatting process. Before formatting your phone, the first thing to consider is to back up important data and files on your phone. To ensure data security, or choose to transfer files to a cloud storage service, you can back it up by connecting to a computer. Use the system's built-in recovery function - simple

Simple and effective steps to resolve 0x80070057 error Simple and effective steps to resolve 0x80070057 error Dec 27, 2023 am 08:38 AM

How to solve 0x80070057 error: simple and effective methods and steps Introduction: In the process of using the computer, we sometimes encounter various error codes. Among them, 0x80070057 is a very common error code, which is usually related to Windows operating system. This error code can appear in different situations, such as when installing or updating the operating system, backing up or restoring files, formatting drives, etc. Although this error code is frustrating, it's not unsolvable. This article will introduce

Will formatting a laptop make it faster? Will formatting a laptop make it faster? Feb 12, 2024 pm 11:54 PM

Will formatting a laptop make it faster? If you want to format your Windows laptop but want to know if it will make it faster, this article will help you know the right answer to this question. Will formatting a laptop make it faster? There are many reasons why users format their Windows laptops. But the most common reason is slow performance or speed of your laptop. Formatting a laptop will completely delete all data stored on the C drive or the hard drive partition where Windows operating system is installed. Therefore, every user will think twice before taking this step, especially when it comes to the performance of the laptop. This article will help you understand whether formatting your laptop will speed it up. Formatting your laptop helps

Computer formatting tutorial Computer formatting tutorial Jan 08, 2024 am 08:21 AM

Many times when using a computer, you will encounter too much garbage, but many users still don’t know how to format the computer. It doesn’t matter. Here is a tutorial on computer formatting for you to take a look at. How to format a computer: 1. Right-click "This PC" on the desktop and click "Manage". 2. Click "Storage" in "Computer Management" to open "Disk Management". 3. Select the hard drive you want to clean, right-click and select "Format". 4. Check "Perform Quick Format" and click "OK" to start formatting.

See all articles