Add basic number and currency formatting

parent 3f24bf4a
// Default Excel value
const decimalPlaces = 2;
export default function format(v, type='', str=''){
if(type === '' && str === ''){
return basicFormat(v);
}
// TODO: document possible type values somewhere(if not already)?
switch(v.toLowerCase()){
case 'number':
return numberFormat(v);
case 'currency':
return currencyFormat(v);
}
}
/**
......@@ -22,14 +33,58 @@ export function getHigherBound(){
return 1e+9;
};
/**
* Basic auto-formatting for cases when no formatting is set.
* Valid numbers that do not fit into range [abs(lowerBound), abs(higherBound)]
* except zeros will be converted to exponential format.
* @param {*} x - Input value
* @returns {String} String representation of input value
*/
export function basicFormat(x){
var lowerBound = getLowerBound();
var higherBound = getHigherBound();
let lowerBound = getLowerBound();
let higherBound = getHigherBound();
if(Math.abs(x) >= higherBound || Math.abs(x) < lowerBound && Math.abs(x) !== 0){
return x.toExponential();
}
return '' + x;
return x.toString();
};
/**
* Basic number formatting, behaves like Excel number formatting with default
* settings (2 decimal places, no 1000 separator)
* @param {*} x - Input value
* @returns {String} String representation of input value
*/
export function numberFormat(x){
if(isNaN(x)){
throw new Error('Unable to format non-numeric and invalid values!');
} else {
return parseFloat(x).toLocaleString(
undefined, // use OS locale
{
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces
}
);
}
}
/**
* Basic currency formatting, behaves like Excel currency formatting with default
* settings (2 decimal places, russian ruble as a currency suffix)
* @param {*} x - Input value
* @returns {String} String representation of input value
*/
export function currencyFormat(x){
if(isNaN(x)){
throw new Error('Unable to format non-numeric and invalid values!');
} else {
return parseFloat(x).toLocaleString(
undefined, {
style: 'currency', currency: 'RUR'
}
);
}
}
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