Fix errors and add tests

parent 30a48dca
// Default Excel value
const decimalPlaces = 2;
const locale = 'ru-RU';
export default function format(v, type='', str=''){
if(type === '' && str === ''){
......@@ -7,7 +8,7 @@ export default function format(v, type='', str=''){
}
// TODO: document possible type values somewhere(if not already)?
switch(v.toLowerCase()){
switch(type.toLowerCase()){
case 'number':
return numberFormat(v);
case 'currency':
......@@ -48,7 +49,7 @@ export function basicFormat(x){
return x.toExponential();
}
return x.toString();
return x.toLocaleString(); // for proper decimal separator
};
/**
......@@ -62,10 +63,11 @@ export function numberFormat(x){
throw new Error('Unable to format non-numeric and invalid values!');
} else {
return parseFloat(x).toLocaleString(
undefined, // use OS locale
locale,
{
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces
maximumFractionDigits: decimalPlaces,
useGrouping: false
}
);
}
......@@ -82,7 +84,7 @@ export function currencyFormat(x){
throw new Error('Unable to format non-numeric and invalid values!');
} else {
return parseFloat(x).toLocaleString(
undefined, {
locale, {
style: 'currency', currency: 'RUR'
}
);
......
......@@ -16,7 +16,7 @@
"d3": "^4.2.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-es2015": "^6.13.2",
"babel-register": "^6.11.6",
"expect.js": "^0.3.1",
"mocha": "^3.0.0"
......
......@@ -10,4 +10,25 @@ describe('format', ()=>{
expect(format(1e-10)).to.be('1e-10');
expect(format(1e10)).to.be('1e+10');
});
it('should do number formatting', function(){
expect(format(0, 'number')).to.be('0,00');
expect(format(1, 'number')).to.be('1,00');
expect(format(-1, 'number')).to.be('-1,00');
expect(format(1e10, 'number')).to.be('10000000000,00');
expect(format(1.1234, 'number')).to.be('1,12');
expect(format(1.1289, 'number')).to.be('1,13');
expect(() => format('123not-a-number', 'number')).to.throwError();
});
it('should do currency formatting', function(){
// Spaces should be non-breaking(ASCII 160/0xA0)
expect(format(0, 'currency')).to.be('0,00\xa0р.');
expect(format(1, 'currency')).to.be('1,00\xa0р.');
expect(format(-1, 'currency')).to.be('-1,00\xa0р.');
expect(format(1e10, 'currency')).to.be('10\xa0000\xa0000\xa0000,00\xa0р.');
expect(format(1.1234, 'currency')).to.be('1,12\xa0р.');
expect(format(1.1289, 'currency')).to.be('1,13\xa0р.');
expect(() => format('123not-a-number', 'currency')).to.throwError();
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment