How can I convert a float
value into a String
object without implementing any library?
I'd like to avoid using char
array.
How can I convert a I'd like to avoid using |
|||||||||||||||||||||
|
If you want to do it manually, rather than using the standard tools ( A floating point number is made up of two distinct parts - the integer part and the decimal part. For instance the number So what to do? Simple: keep dividing the number by 10 until it is just one digit. But be sure to count the number of times you divide by 10. So the example above would end up as 1.234567 with a divide count of 2. This is the same as the scientific representation, 1.234567×10². So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number. So you end up with "1" and 0.234567 and a count of 2. Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1. Grab the integer portion and add it to your string, then remove it from your number. Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string. You now just keep repeating the same process again and again until the absolute value of the count equals the number of decimal places you want to print. For negative numbers you should start by placing a "-" in your string, then taking the absolute value of the number (the number as a positive). Or you just use the standard library function |
|||
|