Sample input string:
char *str = "12345.567675";
And the desired output if I need the precision of 3 places after decimal point:
str = "12345.568";
Is there a way to do this without converting the string to double and back to string?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
yeah, on high level:
1. search ‘.’ in the string.
2. if the position of ‘.’ + 3 is smaller than the length you done.
3. otherwise, concat the string in the position of ‘.’ + 3.
4. here is tricky: you need to check the next char if exists, (‘.’ + 4), and if it’s value >= 5 goto 4.1 (otherwise goto 5)
4.1. copy the string to a new string that have one more space on the left (cause 9.9999 will be changed to 10.0000 in the ‘4’ loop) and set a pointer (P) to the last char in that string.
4.2. if *P between 0 to 8 add 1 to it and go to 5.
4.3. if *P is 9, set it to zero, move the pointer one left (-1) and goto 4.2
4.4. if *P is ‘.’, move the pointer one left (-1) and goto 4.2
5. remove all the 0 on the right of the decimal point (and the decimal point it self if needed) and you done!!!
6. delete everything, and use the double conversion method…