Hacer un flotador mostrar solo dos decimales


Tengo el valor 25.00 en un float, pero cuando lo imprimo en pantalla es 25.0000000.
¿Cómo puedo mostrar el valor con solo dos decimales?

Author: mskfisher, 2009-02-18

13 answers

No es una cuestión de cómo se almacena el número, es una cuestión de cómo se está mostrando. Al convertirlo en una cadena debe redondear a la precisión deseada, que en su caso es de dos decimales.

Ej:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];

%.02f le dice al formateador que va a formatear un flotador (%f) y, que debe ser redondeado a dos lugares, y debe ser rellenado con 0s.

Ej:

%f = 25.000000
%.f = 25
%.02f = 25.00
 627
Author: Andrew Grant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 14:15:35

Aquí hay algunas correcciones -

//for 3145.559706

Swift 3

let num: CGFloat = 3145.559706
print(String(format: "%f", num)) = 3145.559706
print(String(format: "%.f", num)) = 3145
print(String(format: "%.1f", num)) = 3145.6
print(String(format: "%.2f", num)) = 3145.56
print(String(format: "%.02f", num)) = 3145.56 // which is equal to @"%.2f"
print(String(format: "%.3f", num)) = 3145.560
print(String(format: "%.03f", num)) = 3145.560 // which is equal to @"%.3f"

Obj-C

@"%f"    = 3145.559706
@"%.f"   = 3146
@"%.1f"  = 3145.6
@"%.2f"  = 3145.56
@"%.02f" = 3145.56 // which is equal to @"%.2f"
@"%.3f"  = 3145.560
@"%.03f" = 3145.560 // which is equal to @"%.3f"

Y así sucesivamente...

 181
Author: Vaibhav Saran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-28 08:50:08

También puede intentar usar NSNumberFormatter:

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.##";
NSString* s = [nf stringFromNumber: [NSNumber numberWithFloat: myFloat]];

Es posible que también necesite establecer el formato negativo, pero creo que es lo suficientemente inteligente como para averiguarlo.

 20
Author: Rick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-22 17:54:00

En el lenguaje Swift, si desea mostrar que necesita usarlo de esta manera. Para asignar un valor doble en UITextView, por ejemplo:

let result = 23.954893
resultTextView.text = NSString(format:"%.2f", result)

Si desea mostrar en el REGISTRO como objective-c lo hace usando NSLog (), entonces en el lenguaje Swift puede hacerlo de esta manera:

println(NSString(format:"%.2f", result))
 9
Author: imti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-20 18:29:24

Hice una extensión rápida basada en las respuestas anteriores

extension Float {
    func round(decimalPlace:Int)->Float{
        let format = NSString(format: "%%.%if", decimalPlace)
        let string = NSString(format: format, self)
        return Float(atof(string.UTF8String))
    }
}

Uso:

let floatOne:Float = 3.1415926
let floatTwo:Float = 3.1425934
print(floatOne.round(2) == floatTwo.round(2))
// should be true
 7
Author: codingrhythm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-05 10:20:18

EN objective-c, si está tratando con matrices char regulares (en lugar de punteros a NSString) también podría usar:

printf("%.02f", your_float_var);

OTOH, si lo que quieres es almacenar ese valor en un array char puedes usar:

sprintf(your_char_ptr, "%.02f", your_float_var);
 3
Author: Pablo Santa Cruz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-18 10:48:33

El problema con todas las respuestas es que multiplicar y luego dividir resulta en problemas de precisión porque se utilizó la división. Aprendí esto hace mucho tiempo de la programación en un PDP8. La forma de resolver esto es:

return roundf(number * 100) * .01;

Así, 15.6578 devuelve solo 15.66 y no 15.6578999 o algo no intencionado como eso.

El nivel de precisión que desea depende de usted. Simplemente no divida el producto, multiplíquelo por el equivalente decimal. No se requiere ninguna conversión de cadena divertida.

 2
Author: ztalbot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-13 17:09:51

En objective-c es u desea mostrar el valor flotante en 2 números decimales y luego pasar el argumento que indica cuántos puntos decimales desea mostrar por ejemplo, 0.02 f imprimirá 25.00 0.002 f imprimirá 25.000

 1
Author: shaunak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-13 04:51:02

Aquí hay algunos métodos para formatear dinámicamente de acuerdo con una precisión:

+ (NSNumber *)numberFromString:(NSString *)string
{
    if (string.length) {
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        f.numberStyle = NSNumberFormatterDecimalStyle;
        return [f numberFromString:string];
    } else {
        return nil;
    }
}

+ (NSString *)stringByFormattingString:(NSString *)string toPrecision:(NSInteger)precision
{
    NSNumber *numberValue = [self numberFromString:string];

    if (numberValue) {
        NSString *formatString = [NSString stringWithFormat:@"%%.%ldf", (long)precision];
        return [NSString stringWithFormat:formatString, numberValue.floatValue];
    } else {
        /* return original string */
        return string;
    }
}

Por ejemplo

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:4];

=> 2.3453

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:0];

=> 2

[TSPAppDelegate stringByFormattingString:@"2.346324" toPrecision:2];

= > 2.35 (redondear)

 1
Author: Ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 22:33:32

Otro método para Swift (sin usar NSString):

let percentage = 33.3333
let text = String.localizedStringWithFormat("%.02f %@", percentage, "%")

P.d. esta solución no funciona con CGFloat tipo solo probado con Float & Double

 1
Author: Aks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-31 13:10:13

Use NSNumberFormatter con maximumFractionDigits de la siguiente manera:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

Y obtendrás 12.35

 1
Author: Allen Huang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-11 08:29:34

Si también necesita un valor flotante:

NSString* formattedNumber = [NSString stringWithFormat:@"%.02f", myFloat];
float floatTwoDecimalDigits = atof([formattedNumber UTF8String]);
 0
Author: loretoparisi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-10 19:02:17
 lblMeter.text=[NSString stringWithFormat:@"%.02f",[[dic objectForKey:@"distance"] floatValue]];
 0
Author: Rinju Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-03 06:38:46