Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
its working fine that i have tried but after decimal it is not taking 0

What I have tried:

function ParseFloat(str, val) {
  str = str.toString();
  if (Number.isInteger(Number(str))) {
    return Number(str);
  } else {
    str = str.slice(0, str.indexOf(".") + val + 1);
  }
  return Number(str);
}
Posted
Updated 12-Oct-22 19:08pm
Comments
Member 8428760 10-Oct-22 16:32pm    
try parseFloat(str).toFixed(4)

1 solution

You can achieve this through different ways. Few are:
1. using .toFixed()
JavaScript
let num = 5.567891;
let n = num.toFixed(4); //5.5679

// if value is text type
parseFloat("5.567891").toFixed(4);

Refer: JavaScript toFixed() Method[^]

2. using Math.round()
JavaScript
console.log(Math.round(5.95123*10000)/10000); //5.9512

Refer: Math.round() - JavaScript | MDN[^]

Above two should be good enough to achieve most cases. Not suggesting using Number.EPSILON for now. Though if you need precision rounding off, you can refer to: Number.EPSILON - JavaScript | MDN[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900