Last active
April 20, 2016 08:25
-
-
Save thomasfl/9c8cf3ab4edb5cc600ff622b00aaf0c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Currency = React.createClass({ | |
propTypes: { | |
amount: React.PropTypes.number, | |
currencyCode: React.PropTypes.string, | |
decimalPlaces: React.PropTypes.number | |
}, | |
formatCurrency: function (x, decimalPlaces, decimalSeparator, groupSeparator) { | |
var parts = x.toString().split('.'); | |
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator); | |
if(parts.length > 1) { | |
parts[1] = parts[1] + '00000000'; | |
parts[1] = parts[1].substring(0, decimalPlaces); | |
} else { | |
parts[1] = '000000000'.substring(0, decimalPlaces); | |
} | |
return parts.join(decimalSeparator); | |
}, | |
render: function() { | |
var amount = '0.0000000'; | |
var decimalSeparator = ','; | |
var groupSeparator = ' '; | |
var decimalPlaces = 2; | |
var currencyCode = ''; | |
if(typeof(this.props.amount) !== 'undefined') { | |
amount = this.props.amount; | |
} | |
if(typeof(this.props.currencyCode) !== 'undefined') { | |
currencyCode = this.props.currencyCode; | |
} | |
if(typeof(this.props.decimalPlaces) !== 'undefined') { | |
decimalPlaces = this.props.decimalPlaces; | |
} | |
/* A few countries uses period as decimal separator and comma as group separator */ | |
if(currencyCode.match(/USD|GBP|THB/i) !== null) { | |
decimalSeparator = '.'; | |
groupSeparator = ','; | |
} | |
var amountFormatted = this.formatCurrency(amount, decimalPlaces, decimalSeparator, groupSeparator); | |
if(currencyCode !== '') { | |
amountFormatted = amountFormatted + ' ' + currencyCode; | |
} | |
return <span>{amountFormatted}</span> | |
} | |
}); | |
var App = React.createClass({ | |
render: function() { | |
return <div> | |
<h3>Currency formatting component</h3> | |
<ul> | |
<li>No amount or currencyCode: <Currency/></li> | |
<li>Only amount: <Currency amount="1234"/></li> | |
<li>With currencyCode: <Currency amount="1234" currencyCode="EUR"/></li> | |
<li>Use decimalPlaces if other than the default 2: <Currency amount="1234" decimalPlaces="3"/></li> | |
<li>USD/UK decimal and group separator: <Currency amount="1234" currencyCode="USD"/></li> | |
</ul> | |
</div> | |
} | |
}); | |
React.render(<App />, document.body); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple react component for currency formatting.