我有2种价格格式的案例,我被卡在正则表达式上,找不到任何解决方案。
我用来格式化价格的正则表达式:/(\d)(\d{3})(\.)/g
var price = '1000000.0000';
var decimals = 2;
var thousandSeparator = ',';
var decimalSeparator = '.';
var formatedPrice = price.replace(/(\d)(\d{3})(\.)/g, '$1' + thousandSeparator + '$2' + decimalSeparator + '');
document.querySelector( '#case_1 span' ).innerHTML = formatedPrice;
结果:1000,000.0000
预期:1,000,000.0000
var price = '1000000.0000';
var decimals = 2;
var thousandSeparator = '.';
var decimalSeparator = ',';
var formatedPrice = price.replace(/(\d)(\d{3})(\.)/g, '$1' + thousandSeparator + '$2' + decimalSeparator + '');
document.querySelector( '#case_2 span' ).innerHTML = formatedPrice;
结果:1000.000,0000
预期:1.000.000,0000
JsFiddle:https://jsfiddle.net/cpan2s6d/
是否可以仅使用正则表达式来实现?
谢谢
答案 0 :(得分:1)
尝试一下:
首先用小数点分隔符替换所有点。然后将数千人分组。
import sys
import os
#List of weekdays
weekdays = ['Monday' ,'Tuesday' ,'Wednesday', 'Thursday' , 'Friday' ,'Saturday', 'Sunday']
print('Enter Your DOB as DD/MM/YYYY: ')
day = input("Day: ")
month = input("Month: ")
X = ''
#Check for month
if month in ['02' , '04', '06', '09', '11']:
i = 30
X = 'Answer'
Y = input("Year: ")
if (len(Y)) < 4:
print('You Have Entered A Too Short Or Too Long of a Year')
sys.exit(0)
if X == 'Answer':
print('This Is True')
elif X != 'Answer':
print('This is False')
print("You Were Born On A:")
input("Press ENTER To Exit")
代码:
price.replace(".", decimalSeparator).replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
var price = '1000000.00';
var decimals = 2;
var thousandSeparator = ',';
var decimalSeparator = '.';
var formatedPrice = price.replace(".", decimalSeparator).replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
document.querySelector('#case_1 span').innerHTML = formatedPrice;
var price = '1000000.00';
var decimals = 2;
var thousandSeparator = '.';
var decimalSeparator = ',';
var formatedPrice = price.replace(".", decimalSeparator).replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
document.querySelector('#case_2 span').innerHTML = formatedPrice