# how to convert float like 0.333333 to string "1/3"

Get help using Construct 2

### » Sat Mar 09, 2013 5:56 pm

Hello,I have a problem in process math calculate:
How to convert a float like 0.33333333 to percent string "1/3"?

like:
0.333333333333 -> "1/3"
0.666666666666 -> "2/3"

and how to determine transfer Infinity number (ie. result of 1/0) to a special string like "NA"?

thanks.
B
3
Posts: 6
Reputation: 337

### » Sat Mar 09, 2013 6:14 pm

Have a look here: dec2fract.html
B
67
S
19
G
121
Posts: 3,196
Reputation: 72,879

### » Sat Mar 09, 2013 8:17 pm

Decide how forgiving you want to be, then create some fun if statements!

If x <.334 and x > .332 string = "1/3"
if x = .25 string ="1/4"
if x < .1668 and x > .1666 string = "1/6"

do this for every possible fraction you care about.

would be smartest to create a function to contain these checks as well.

FUNction

function string decimalToFraction(x){
if if if ...
return string;
}cincipon2013-03-09 20:19:21
B
6
S
1
G
1
Posts: 70
Reputation: 702

### » Sun Mar 10, 2013 2:28 am

thanks. but the float is result of some calculating, ie. 2.333333 is result of 8/3.
so that float number is indefinite. how can i transfer it to a frac string
2.333333 -> 8/3?
it cannot be solved by "if else" condition.
blackhornet supply a good idea, is there a simple method or function? thanks more.
B
3
Posts: 6
Reputation: 337

### » Sun Mar 10, 2013 3:10 am

I am almost certain that there is no simple function. The simple method is as I described. Decide upon a precision threshold, and check the digits to the right of the decimal place. There is a method to truncate into an integer, so you can make two strings and concatenate them. so your 8/3 as 2.333333 becomes 2 and 1/3.
B
6
S
1
G
1
Posts: 70
Reputation: 702

### » Sun Mar 10, 2013 3:11 am

The reason is that .3333333333333333333 is not 1/3. It is an approximation of 1/3, and to go between the two needs some human judgement, e.g. IF statements.
B
6
S
1
G
1
Posts: 70
Reputation: 702

### » Sun Mar 10, 2013 9:34 am

i mean that float is accurate of 1/3. the problem is how to transfer a repeating decimals (0.33333333) to fraction express (1/3) in order to show ?
B
3
Posts: 6
Reputation: 337

### » Sun Mar 10, 2013 12:19 pm

Computers don't use that notation as they usually deal in decimals. Fractions are just our way of simplifying how we read it. So I doubt there is a "simple" way, but someone may have written a javascript library to handle that type of thing for some type of math learning app. So you may be ale to find one and write a plugin for it. But C2 most likely doesn't have a built in easy way as that isn't really a common gaming requirement.
B
49
S
11
G
10
Posts: 1,833
Reputation: 14,418

### » Sun Mar 10, 2013 2:51 pm

thanks a lot. i'll try some method.
B
3
Posts: 6
Reputation: 337

### » Sun Mar 10, 2013 5:28 pm

This javascript example will get you on your way if you want to make a plugin to do it.

B
6
S
1
G
1
Posts: 70
Reputation: 702

Next