I have the following string.
var string = '14,12.1545';
In the above variable I need to take two decimals after dot. How to split the variable with dot.
the expected output is 14,12.15
I have the following string.
var string = '14,12.1545';
In the above variable I need to take two decimals after dot. How to split the variable with dot.
the expected output is 14,12.15
From a pure string manipulation point of view: separate the string into two parts, one before the dot and one after. Use slice
to select only the first two characters of the after-string, and then put them back together.
function translateString(input) {
const [beforeDot, afterDot] = input.split('.');
const afterDotTrimmed = afterDot.slice(0, 2);
return beforeDot + '.' + afterDotTrimmed;
}
console.log(translateString('14,12.1545'));
console.log(translateString('14,12.1'));
console.log(translateString('14,12.154534534534'));
You could also use a regular expression:
function translateString(input) {
return input.replace(/\.(\d{1,2}).*$/, '.$1');
}
console.log(translateString('14,12.1545'));
console.log(translateString('14,12.1'));
console.log(translateString('14,12.154534534534'));
Convert it to array and make the changes
let str='14,12.1123,3.1415926554';
let arr=str.split(",");
let n=arr.map(a=>a.indexOf('.') !== -1 ? parseFloat(a).toFixed(2) : parseFloat(a));
console.log(n.join(","));
You can borrow a suitable number formatter from previous answers, like this: How can I format numbers as dollars currency string in JavaScript?
Then you can change your text to a number and format it. I assume that you want round from half up, like this:
// suitable answer from question 149055
Number.prototype.format = function(n, x) {
var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};
var string = '14,12.1545'
var number = parseFloat(string.replace(/,/g , ""))
console.log(number.format(2, 2)) // -> 14,12.15
string = '99,99.9999'
number = parseFloat(string.replace(/,/g , ""))
console.log(number.format(2, 2)) // -> 1,00,00.00