diff options
-rw-r--r-- | tikzit/src/common/Graph.m | 4 | ||||
-rw-r--r-- | tikzit/src/common/util.h | 9 | ||||
-rw-r--r-- | tikzit/src/common/util.m | 23 |
3 files changed, 33 insertions, 3 deletions
diff --git a/tikzit/src/common/Graph.m b/tikzit/src/common/Graph.m index 258ece4..2d07ccc 100644 --- a/tikzit/src/common/Graph.m +++ b/tikzit/src/common/Graph.m @@ -720,8 +720,8 @@ [code appendFormat:@"\t\t\\node %@ (%d) at (%@, %@) {%@};\n", [[n data] tikzList], i, - [NSNumber numberWithFloat:[n point].x], - [NSNumber numberWithFloat:[n point].y], + formatFloat([n point].x, 4), + formatFloat([n point].y, 4), [n label] ]; i++; diff --git a/tikzit/src/common/util.h b/tikzit/src/common/util.h index f527820..b34f25d 100644 --- a/tikzit/src/common/util.h +++ b/tikzit/src/common/util.h @@ -191,4 +191,11 @@ NSString *alphaHex(unsigned short sh); const char *find_start_of_nth_line (const char * string, int line); -// vi:ft=objc:noet:ts=4:sts=4:sw=4 +/*! + @brief Formats a CGFloat as a string, removing trailing zeros + @detail Unlike formatting an NSNumber, or using %g, it will never + produce scientific notation (like "2.00e2"). Unlike %f, + it will not include unnecessary trailing zeros. + */ +NSString *formatFloat(CGFloat f, int maxdps); + diff --git a/tikzit/src/common/util.m b/tikzit/src/common/util.m index aa21a67..e9b8899 100644 --- a/tikzit/src/common/util.m +++ b/tikzit/src/common/util.m @@ -376,5 +376,28 @@ const char *find_start_of_nth_line (const char * string, int line) { return lineStart; } +NSString *formatFloat(CGFloat f, int maxdps) { + NSMutableString *result = [NSMutableString + stringWithFormat:@"%.*f", maxdps, f]; + // delete trailing zeros + NSUInteger lastPos = [result length] - 1; + NSUInteger firstDigit = ([result characterAtIndex:0] == '-') ? 1 : 0; + while (lastPos > firstDigit) { + if ([result characterAtIndex:lastPos] == '0') { + [result deleteCharactersInRange:NSMakeRange(lastPos, 1)]; + lastPos -= 1; + } else { + break; + } + } + if ([result characterAtIndex:lastPos] == '.') { + [result deleteCharactersInRange:NSMakeRange(lastPos, 1)]; + lastPos -= 1; + } + if ([@"-0" isEqualToString:result]) + return @"0"; + else + return result; +} // vi:ft=objc:noet:ts=4:sts=4:sw=4 |