在点后分割一个带小数点后2位的字符串

时间:2018-04-28 09:33:50

标签: javascript

我有以下字符串。

var string = '14,12.1545';

在上面的变量中,我需要在点之后取两位小数。如何用点分割变量。

预期输出为14,12.15

3 个答案:

答案 0 :(得分:3)

从纯字符串操作的角度来看:将字符串分成两部分,一部分在点之前,一部分在之后。使用import { userRedirect } from 'ui/client/helpers/userRedirect'; const loadUserEpic = action$ => action$.ofType('LOAD_USER').pipe( mergeMap(() => Observable.of( { type: 'FETCH_USER_CONFIG' }, { type: 'FETCH_USER_MODULES' }, { type: 'FETCH_USER_DIVISION' }, userRedirect() ) ) ); const userConfigEpic = action$ => action$.ofType('FETCH_USER_CONFIG').mergeMap(() => fromPromise(axios.get(`/me/configuration`)) .map(response => ({ type: 'FETCH_USER_CONFIG_SUCCESS', data: response.data })) .catch(error => Observable.of({ type: 'FETCH_USER_CONFIG_ERROR', error }) ) ); const userModulesEpic = action$ => action$.ofType('FETCH_USER_MODULES').mergeMap(() => fromPromise(axios.get(`/me/modules`)) .map(response => ({ type: 'FETCH_USER_MODULES_SUCCESS', data: response.data })) .catch(error => Observable.of({ type: 'FETCH_USER_MODULES_ERROR', error }) ) ); const userDivisionEpic = action$ => action$.ofType('FETCH_USER_DIVISION').mergeMap(() => fromPromise(axios.get(`/division/`)) .map(response => ({ type: 'FETCH_USER_DIVISION_SUCCESS', data: response.data })) .catch(error => Observable.of({ type: 'FETCH_USER_DIVISION_ERROR', error }) ) ); 仅选择后字符串的前两个字符,然后将它们重新组合在一起。



slice




您还可以使用正则表达式:



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'));




答案 1 :(得分:1)

将其转换为数组并进行更改

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(","));

答案 2 :(得分:1)

您可以从以前的答案中借用合适的数字格式器,如下所示: How can I format numbers as dollars currency string in JavaScript?

然后,您可以将文本更改为数字并进行格式化。我假设你想从一半上升,像这样:

// 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