简体   繁体   中英

How to format float in C without most significant digits?

I wanna output data look like this

input : 1999.99
output: 999.99 

I wanna cut out the more significant digits.

I have been used C format like this

%.2f  ==> 10.44, 23.23, 5.67

And now i need to cut before decimal point.

Is any solution?

Truncating extra high order digits as requested can be obtained using the fmod() function:

#include <math.h>
#include <stdio.h>

void format_3_2(double input) {
    printf("%.2f", fmod(input, 1000.0));
}

input: 1999.99
output: 999.99

Note however that you should also round the input value before applying the fmod() function to avoid this: printf("%.2f", fmod(1999.999, 1000.0)); -> 1000.00 . Use the round function for this:

#include <math.h>
#include <stdio.h>

void format_3_2(double input) {
    printf("%.2f", fmod(round(input * 100.0) / 100.0, 1000.0));
}

input: 1999.999
output: 0.00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM