Hey Miri,
your post is a perfect example why it is important to write tests. Thanks for sharing!
I really liked your dead simple test setup.
At my work place we usually don't write tests, but I sometimes copy a function into jsfiddle to quickly throw in a bunch of inputs to check the expected outcome.
I did so with your problem and had a shot at implementing the algorithm myself.
I noticed that there are further cases that you might not have thought of.
Negative numbers and numbers with a decimal portion result in errors in your implementation.
here is my solution:
functionformatNumberAsCurrencyEuro_Tobi(value){if(typeofvalue==='string'){returnvalue;}letformattedValue='';// these should be function parametersconstthousandsSeparator='.';constdecimalSeparator=',';constcurrencyName='Euro';letvalueString=String(_.round(value,2));// lodash.roundletdecimalString='';if(valueString.indexOf('.')!==-1){// has decimal portionconstsplittedValue=valueString.split('.');valueString=splittedValue[0];decimalString=decimalSeparator+splittedValue[1];}for(vari=0;i<valueString.length;i++){varcurrentChar=valueString[valueString.length-1-i];if(i!==0&&i%3===0&¤tChar!=='-'){formattedValue=thousandsSeparator+formattedValue;}formattedValue=currentChar+formattedValue;}returnformattedValue+decimalString+''+currencyName;}
Another approach would be to simply use the toLocaleString() function.
Probably the easiest and best solution:
Hey Miri,
your post is a perfect example why it is important to write tests. Thanks for sharing!
I really liked your dead simple test setup.
At my work place we usually don't write tests, but I sometimes copy a function into jsfiddle to quickly throw in a bunch of inputs to check the expected outcome.
I did so with your problem and had a shot at implementing the algorithm myself.
I noticed that there are further cases that you might not have thought of.
Negative numbers and numbers with a decimal portion result in errors in your implementation.
here is my solution:
Another approach would be to simply use the toLocaleString() function.
Probably the easiest and best solution:
Funnily, even this function has the erroneous test case of
-0
as an input.Whole jsfiddle with running tests:
jsfiddle.net/tobiobeck/p35ebLvs/