how to convert 1,800.00 to 1800 in javascript? [duplicate] - javascript

This question already has answers here:
How to convert a number with comma as string into float number in Javascript
(2 answers)
Closed 4 years ago.
I am trying to convert 1,100.00 or 1,800.00 to 1100 or 1800 by using Javascript Number() function but it gives NaN.
For Example:
var num = "1,100.00";
console.log(Number(num));
output: NaN
My requirement is If I have a number 1,800.00 it should convert to 1800 in Javascript.
Any help will be appreciated.
Thanks.

You can replace the , char using built-in replace function and then just convert to Number.
let number = "1,100.00";
console.log(Number(number.replace(',','')));

The Number() function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned.
You might have multiple , in the string replace all , from the string before passing to Number():
let numStr = '1,800.00';
let num = Number(numStr.replace(/,/g,''));
console.log(num);
.as-console-wrapper{
top: 0;
}

You can just replace the , with empty '' and then convert the string into number with + operator
let neu = "6,100.00";
document.write(+neu.replace(',',''));

You can try this.
var myValue = '1,800.00';
var myNumber = myValue.replace(/[^0-9.]/g, '');
var result = Math.abs(myNumber);
console.log( Math.floor(myNumber))
Here, in myValue, only number is taken removing other characters except dot.
Next thing is the value is converted to positive number using Math.abs method.
And at last using Math.floor function the fraction part is removed.

Related

Javascript convert string value to Int value or Float [duplicate]

This question already has answers here:
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed last month.
I want to convert string to Int or float type in JavaScript below is my code. or any solution is there in react library?
var a = '23,34.0';
console.log(parseFloat(a)); // 23
console.log(parseInt(a)) // 23
I want output like this:
`var a = '23,34.0';
output :
23,34.0 as a integer
I tried below codes
parseInt(a) parseFloat(a) Number(a)
this methods I tried but am not exact outputs.
Since your string is not a valid number, you cannot convert it.
You have to pass a valid number like 2324.5 to convert.
Trying this
var a = '2334.5'
console.log(parseFloat(a))
console.log(parseInt(a))
You will get 2334.5 and 2334 as output. "parseInt" will still yet cut of everything after the decimal point, because that's what an integer is, a whole number.

How do u add 2decimals points into this function code in javascript? [duplicate]

This question already has answers here:
Format number to always show 2 decimal places
(37 answers)
Closed 1 year ago.
function calculateTotal() {
document.getElementById("Total1").value = document.getElementById("Unit1").value * document.getElementById("quantity1").value
}
First make sure the values of inputs are numbers by parse Float()
Then you can use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal.
The elements don't have a .value property, instead you can use .textContent to get and change the value stored.
If you are working with numbers only, you can use .toFixed() to round the product.
const quantityEl = document.getElementById("quantity1");
const unitEl = document.getElementById("unit1");
// .toFixed() takes a parameter for number of digits to appear after decimal, in this case 2
const val = (quantityEl.textContent * unitEl.textContent).toFixed(2);
document.getElementById("value").textContent = val;

Write a JavaScript function that reverse a number [duplicate]

This question already has answers here:
JavaScript: How to reverse a number?
(19 answers)
Closed 3 years ago.
Result shows "n.split is not a function" unless i include n=n+" " the following code.What does third line mean?
function reverse_a_number(n)
{
n = n + "";
return n.split("").reverse().join("");
}
console.log(reverse_a_number(32243));
There is no split function in Number.prototype. So, n = n + "" is just a simple way to convert a number to a string.
From the spec
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
If one of the operands in an expression with + is a string, the other operand is also coerced to a string and concatenated with it
console.log( 1 + 1 ) // sum
console.log( 1 + "1" ) // concatenation
console.log( true + "string" ) // concatenation
In javascript , there is no Explicit declaration of datatype, by assigning value to the variable , it implicitly takes the datatype like int,string.
In your case,Simple you are applying String function to integer , so you are getting Error.
So first convert integer value into String by using "toString()" function.
Solution:
function reverse_a_number(n) {
//Casting
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
There is no split function for Number. You can do this as an alternate
+String.prototype.split.call(32243,'').reverse().join('')
What the above code does?
I am using split method in String class via context switching for number which returns array.
Then we are reversing the number and joining it.
Then unary plus converts it to number.
As #briosheje mentioned, you can also use the following
+[...''+32243].reverse().join('')
Cast the number to a string and then use split as numerical values don't have the split function. Again cast it to a number while returning
function reverse_a_number(n) {
n=n.toString();
return Number(n.split("").reverse().join(""));
}
console.log(reverse_a_number(32243));
The reason is that split method works only on string values and your passing integer value as argument, that's why it's working only after casting it to string
You can't split a number. By using n = n + "", you're casting it a string and then splitting it. However, you're also returning a string! You'll want to cast it back to an integer before you return it.
Hmm.. I think this could be solved easily.
turn the number to a string, this lets you turn it to an array
Split it to a array
use array's function 'reversed'
join it
turn it to an number or int again.
const number = 3211232;
const numberReversed = parseInt(number.toString().split("").reverse().join(""));
console.log(numberReversed);

parseInt fixing the value

Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.

Javascript: using toLocaleString + Tofixed

I need to format a number for a project im working on at work, only problem is that I cant format it how i want.
I convert the number to a localestring using the toLocaleString method which gives me the commas but i also need decimal places, nothing i seem to do works.
var number = 123.322
number = parseFloat(number).toFixed(2) //123.22
number.toLocaleString() //123.22
The above code just returns the parsefloated number along with the tofixed decimal values but it doesn't add the commas.
How do i get a number to have two decimal places (when the value is 'xx.00') and also be comma separated. Is this possible in JavaScript?
You can give an object to .toLocaleString() which describes what you want:
var sNumber = (10123.322).toLocaleString(undefined,
{'minimumFractionDigits':2,'maximumFractionDigits':2});
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Original:
const fNumber = 10123.322;
const sNumber = parseFloat(fNumber.toFixed(2)).toLocaleString();
console.log(sNumber);
The number is already in decimal/float format on the first line.
.toFixed(2) turns it into a string using fixed-point notation.
parseFloat() takes that string and turns it back into a float.
.toLocaleString() turns it into a string using the local format.
Just to do it in one line
var num = '12233.3366554';
num = parseFloat(parseFloat(num).toFixed(2)).toLocaleString('en-IN', { useGrouping: true });
Yes, it is possible using .toLocaleString, yo just need to specify the language, optionally you can specify decimals and currency. look at this example:
35000.2455.toLocaleString('en-IN', {minimumFractionDigits: 2, maximumFractionDigits: 2,style: 'currency', currency: 'USD' })
this returns $35,000.25
Number.toLocaleString works on a number, but toFixed returns a string.
Coerce the string back into a number first
var number = 123.322;
var string = parseFloat(number).toFixed(2);
var parsed = (+string).toLocaleString();
console.log(parsed);
In order to get commas you have to specify the locale .The locale en includes commas for the numbers. toFixed() Returns a string. toLocaleString() function commas works on a number not on a string.So parse the string to float.
var number = 1234567.322;
number = parseFloat(parseFloat(number).toFixed(2)).toFixed(2) ;
number=number.toLocaleString('en');
toLocaleString function provide number representation based on languages
var number = 3500.00;
if(Number.isInteger(number)){
var zeroappend= number.toLocaleString()+".00";
console.log(zeroappend);//3,500.00;
}else{
console.log(number.toLocaleString());
}

Categories

Resources