ParseFloat reemplacement with a limit of decimals to show


/ Published in: JavaScript
Save to your folder(s)

This snippet is a reemplacement for the parseFloat function of the Javascript language. This new function gets one or two parameters if only one parameter is defined the function is like the original parseFloat. If there are two parameter passed to the function, the first parameter must be a string or number and the second parameter must be the number of decimals we want to get, if the last decimal is greater or equal than five the last decimal is incremented by one.


Copy this code and paste it in your HTML
  1. var proxyFloat = window.parseFloat;
  2. window.parseFloat = function(number,nDecimals){
  3. var amischol = true;
  4. var stringNumber = number.toString(), lastDec, posFinal, numberMore, result, decimalType, decimals;
  5. var decimalTypes = [".",","];
  6. for(var i = 0; i < decimalTypes.length; i++){
  7. pos = stringNumber.indexOf(decimalTypes[i]);
  8. if(pos != -1){
  9. decimalType = decimalTypes[i];
  10. break;
  11. }
  12. }
  13.  
  14. decimals = (stringNumber.length-1)-pos;
  15. if(typeof nDecimals != "undefined"){
  16. decimals = nDecimals;
  17. }
  18. posFinal = pos+(decimals+1);
  19. if(pos != -1){
  20. lastDec = stringNumber.substr(posFinal,1);
  21. stringNumber = stringNumber.substr(0,posFinal);
  22. if(lastDec >= 5){
  23. numberMore = stringNumber.substr(stringNumber.length-1,1);
  24. if(numberMore == decimalType){
  25. stringNumber = (stringNumber.substr(0,stringNumber.length-1)*1)+1;
  26. }else{
  27. stringNumber = stringNumber.substr(0,stringNumber.length-1)+((numberMore*1)+1);
  28. }
  29.  
  30. }
  31. }
  32. result = proxyFloat(stringNumber);
  33. return result;
  34. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.