i have a string like this 21600.00 how do I delete 00 after the dot?
I've tried it like this
replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
but '.00' is not erased, so the assumption that I expect is like this 21,600 or 8,000 etc.
You could try any of these:
const str = '21600.00'
console.log(new Intl.NumberFormat('en-US').format(str));
console.log(Number(str).toLocaleString('en-US'))
console.log(str.slice(0,-3))
console.log(str.split('.')[0])
console.log(str.substring(0, str.indexOf('.')))
console.log(`${Math.round(str)}`)
console.log(`${Math.trunc(str)}`)
console.log(`${parseInt(str)}`)
console.log(Number(str).toFixed())
You can simply use parseInt function to remove .00 This will show the exact number without any zeros added.
If you want to convert back to string format you can use toString() to do that.
If you want to add commas format you can use toLocaleString
Run snippet below.
let string = '21600.00'
//Use parse Int
let int = parseInt(string)
console.log(int.toString()) //Returns string
console.log(int) //Returns number
console.log(int.toLocaleString()) //Returns number with comma added
You can try this.
var decimal = 21600.00;
var numString = decimal.toString().split('.')[0];
var integer = parseInt(numString);
console.log(integer);
console.log(Number(numString).toLocaleString('en-US'));
Related
For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?
Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));
new String(your_number).substring(0,6)
(basically converting it to a string and substringing it). Don't forget to parse it back afterwards
Applicable only when you want to strip last 7 digits, and the numbers have constant length (13 in this case). Still leaving you with first 6 ones though.
const nr = 1517778188788;
const result = Math.floor(nr / 10000000)
Try this:
var num = 1517778188788; // long number
var str = num.toString(); //convert number to string
var result = str.substring(0,6) // cut six first character
result = parseInt(result); // convert it to a number
here is a working fiddle
I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.
var number = 134324;
var num_str = number + "";
console.log(num_str);
No it should not return string .. as you are printing it in console it looks like integer but try using
var number = 134324;
var num_str = number + "";
console.log(num_str);
typeof(num_str);
It will display that your answer is string ... :) hope you satisfied ..
You can use toString() method.
num_str = number.toString()
i am trying to parse a float in javascript in this way:
var number = '25.492.381';
var cost = parseFloat(number);
This returns 25.492
I wish this would return 25.492.381
How can this be done?
Remember that . in standard notation split the Integer and Fractional part of the number. You could want this:
var number = '25.492.381'.replace('.', '').replace(",",".") ;
var cost = parseFloat(number);
25.492.381 is not a float. You need to use a formatter.
Check Numbro
This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.
I want to remove commas from the string and calculate those amount using JavaScript.
For example, I have those two values:
100,000.00
500,000.00
Now I want to remove commas from those string and want the total of those amount.
To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));
Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format. This cleans up any bad inputs, if there is one it returns a string of NaN you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace.
ParseFloat converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}
To remove commas, you will need to use string replace method.
var numberArray = ["1000,00", "23", "11"];
//If String
var arrayValue = parseFloat(numberArray.toString().replace(/,/g, ""));
console.log(arrayValue, "Array into toString")
// If Array
var number = "23,949,333";
var stringValue = parseFloat(number.replace(/,/g, ""));
console.log(stringValue, "using String");