javascript - Add thousand seperator and retain decimal place [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to print number with commas as thousands separators in Javascript
I have a function that will add thousand seperators to a number, however it is not working well when a decimal is passed in:
function thousandSep(val) {
return String(val).split("").reverse().join("")
.replace(/(.{3}\B)/g, "$1,")
.split("").reverse().join("");
}
If I pass in 10000, I get 10,000 as expected.
However, passing in 10,000.00 I get 1,000,0.00.
How can I modify the function to handle decimals?

Don't use ., use \d
function thousandSep(val) {
return String(val).split("").reverse().join("")
.replace(/(\d{3}\B)/g, "$1,")
.split("").reverse().join("");
}

function format(n, sep, decimals) {
sep = sep || "."; // Default to period as decimal separator
decimals = decimals || 2; // Default to 2 decimals
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
format(4567354.677623); // 4,567,354.68

Related

How to limit decimal digits in JavaScript output? [duplicate]

This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 5 years ago.
When I am trying to calculate the values
My output has 15 digits in decimal values
Like if x=3
Then in output it is showing
5.196152422706632
But how can I limit it to
5.19615
How to limit decimal digits in output from 15 digits to 5 digits in JavaScript?
Here is my script:
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + Math.sqrt(3)*x + "volts";
}
</script>
How can I use this:
double number = 0.#############;
DecimalFormat numberFormat = new DecimalFormat("#.#####");
The toFixed method allows you to set the number of digits.
I would use it like this:
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3) * x).toFixed(5) + "volts";
Btw, java is a completely different language to javascript - you're not using it here
In javascript you can fix the no of digits you want to display after decimal by using the function - toFixed(n).
Here n specifies the no of digits to display after decimal.
<script>
function myFunction() {
var x = document.getElementById("phase").value;
document.getElementById("demo").innerHTML = "<b>V<sub>L</sub>is</b><br>" + (Math.sqrt(3)*x).toFixed(5) + "volts";
}
</script>
In java you can do it like this.
public static void main(String[] args)
{
String value = String.format("%.3f", Math.sqrt(3)*9);
System.out.println("Value with 3 decimals: " + value);
}
In javascript you should check this anwser.

Digit number and two characters after the point [duplicate]

This question already has answers here:
JavaScript equivalent to printf/String.Format
(59 answers)
Closed 5 years ago.
I have a number, for example:
25297710.1088
I need to add a bit between them and leave two characters after the point.
For example:
25 297 710.10
While I stopped at this:
$(td).text().reverse().replace(/((?:\d{2})\d)/g, '$1 ').reverse());
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
From this code I get the following:
25 297 710.1 088
Where $(td).text() I get a number from the cell of the row in the table.
If I have numbers, for example:
25297710.10
then i get:
25 297 710.10
It's ok.
What I need to do to leave two characters after the point?
You can use a RegExp to format the number/string. The input is converted to string using the relevant toString method.
function formatNumber(input) {
return input.toString().replace(/\d*(\d{2})(\d{3})(\d{3})\.(\d{2})\d*$/, "$1 $2 $3.$4");
}
var str = "25297710.1088";
var num1 = 25297710.1088;
var num2 = 2545454545454.2254;
var num3 = 232545454511112.3354122313123123;
console.log(formatNumber(str));
console.log(formatNumber(num1));
console.log(formatNumber(num2));
console.log(formatNumber(num3));
I think you can do next steps:
1) you have 25 297 710.10
2) you find position of dot symbol ->#pos
3) you replace bits in string in range between #pos and end of your string
4) you cut string after dot to 2 characters

Format a number to a string in javascript [duplicate]

This question already has answers here:
How can I pad a value with leading zeros?
(76 answers)
Closed 9 years ago.
I can't figure out how to solve the following problem.
I have an array of numbers from 1 to 100.
I need to convert them to strings but to a length of 5.
So, for instance:
1 becomes 00001
2 becomes 00002
3 becomes 00003
4 becomes 00004
etc, etc..
It seems so easy but I cannot find a function. The best I found was .toFixed(n) which is the number of decimal points to use.
Here's a very simple padding function:
function padLeft(str, length, paddingCharacter) {
str = '' + str; //Make sure that we convert it to a string if it isn't
while (str.length < length) {
str = paddingCharacter + str; //Pad it
}
return str;
}
padLeft(123, 5, '0'); //00123

Identify if a string has any non-integer characters, in JavaScript [duplicate]

This question already has answers here:
Using JavaScript's parseInt at end of string
(6 answers)
Closed 9 years ago.
JavaScript parseInt() does not seem to work the same way as Java parseInt().
A very simple example is:
document.write(parseInt(" 60 ") + "<br>"); //returns 60
document.write(parseInt("40 years") + "<br>"); //returns 40
document.write(parseInt("He was 40") + "<br>"); //returns NaN
Line 1 is ok. but I expect line 2 to give an error, since you can't actually convert 'years' to an integer. I believe JavaScript parseInt() just checks if the first few characters in a String are an Integer.
So how can I check that as long as there are non-Integers in the String, it will return NaN?
parseInt is designed for some flexibility in parsing integers. The Number constructor is less flexible with extra characters, but will also parse non-integers (thanks Alex):
console.log(Number(" 60 ")); // 60
console.log(Number("40 years")); // Nan
console.log(Number("He was 40")); // NaN
console.log(Number("1.24")); // 1.24
Alternatively, use a regular expression.
" 60 ".match(/^[0-9 ]+$/); // [" 60 "]
" 60 or whatever".match(/^[0-9 ]+$/); // null
"1.24".match(/^[0-9 ]+$/); // null
To check if string contains non-integers, use regex:
function(myString) {
if (myString.match(/^\d+$/) === null) { // null if non-digits in string
return NaN
} else {
return parseInt(myString.match(/^\d+$/))
}
}
I would use a regex, maybe something like the following.
function parseIntStrict(stringValue) {
if ( /^[\d\s]+$/.test(stringValue) ) // allows for digits or whitespace
{
return parseInt(stringValue);
}
else
{
return NaN;
}
}
The simplest way is probably using the unary plus operator:
var n = +str;
This will also parse floating point values though.
Below is an isInteger function that can be added to all String objects:
// If the isInteger function isn't already defined
if (typeof String.prototype.isInteger == 'undefined') {
// Returns false if any non-numeric characters (other than leading
// or trailing whitespace, and a leading plus or minus sign) are found.
//
String.prototype.isInteger = function() {
return !(this.replace(/^\s+|\s+$/g, '').replace(/^[-+]/, '').match(/\D/ ));
}
}
'60'.isInteger() // true
'-60'.isInteger() // true (leading minus sign is okay)
'+60'.isInteger() // true (leading plus sign is okay)
' 60 '.isInteger() // true (whitespace at beginning or end is okay)
'a60'.isInteger() // false (has alphabetic characters)
'60a'.isInteger() // false (has alphabetic characters)
'6.0'.isInteger() // false (has a decimal point)
' 60 40 '.isInteger() // false (whitespace in the middle is not okay)

Multiplication results in unusual decimal places [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?
I have a strange mathematical problem during a multiplication in javascript.
$(parent).find('#id_deals-' + i + '-quantity').val()
result -> 10
$(parent).find('#id_deals-' + i + '-price').val()
result -> 3.99
Both above mulltiplied like this:
$(parent).find('#id_deals-' + i + '-price').val() * $(parent).find('#id_deals-' + i + '-quantity').val()
result --> 39.900000000000006
Why is this happening? and what can I do to limit the decimal places to 2 digits only?
Is it maybe because 10 has to be 10.0 ? But how do I convert my value to this format automatically before the actual multiplication?
Update:
According to syazdani's answer, I have tried to implement bigdecimal as suggested:
It is not well documented, but I got it working like this:
function run(opts) {
var bd = {"BigDecimal":BigDecimal, "BigInteger":BigInteger, "RoundingMode":RoundingMode};
var result;
var ops = {'*': "multiply", '/': "divide", '+': "add", '-': "subtract"};
var a = new bd.BigDecimal("" + opts.a);
var b = new bd.BigDecimal("" + opts.b);
var op = ops[opts.op];
if (op == "divide") {
return a.divide(b, 300, bd.RoundingMode.HALF_UP());
} else {
return a[op].call(a, b);
}
}
function multiply(a, b){
return run({"a":a,"b":b,"op":"*"});
}
If you are working with currency (as it seems that you are given the "price" id), you may be better served by using a so called Big Number library (such as this one: https://github.com/iriscouch/bigdecimal.js) for your math to control the math (round up vs round down, etc.). It takes a bit more work to get everything right, but it is worthwhile to avoid the Office Space math scenario.
All javascript number are IEEE-754 double precision floating points numbers. That means that they suffer from round-off errors and imprecision.
All numbers in javascript are floating point numbers, based on IEEE754.
If you want to format one as a string with a fixed number of digits after the dot, use
var formattedNumber = v.toFixed(2); // this makes a string

Categories